Predict the output of following C++ programs.
Question 1
#include<iostream> using namespace std; class Test1 { int x; public: void show() { } }; class Test2 { int x; public: virtual void show() { } }; int main(void) { cout<<sizeof(Test1)<<endl; cout<<sizeof(Test2)<<endl; return 0; } |
Output:
4
8
There is only one difference between Test1 and Test2. show() is non-virtual in Test1, but virtual in Test2. When we make a function virtual, compiler adds an extra pointer vptr to objects of the class. Compiler does this to achieve run time polymorphism (See chapter 15 of Thinking in C++ book for more details). The extra pointer vptr adds to the size of objects, that is why we get 8 as size of Test2.
Question 2
#include<iostream> using namespace std; class P { public: virtual void show() = 0; }; class Q : public P { int x; }; int main(void) { Q q; return 0; } |
Output: Compiler Error
We get the error because we can’t create objects of abstract classes. P is an abstract class as it has a pure virtual method. Class Q also becomes abstract because it is derived from P and it doesn’t implement show().
Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above.
Recommended Posts:
- Output of C++ Program | Set 1
- Output of C Program | Set 17
- Output of C++ Program | Set 2
- Output of C++ Program | Set 3
- Output of C Program | Set 18
- Output of C Program | Set 19
- Output of C Program | Set 20
- Output of C++ Program | Set 4
- Output of C++ Program | Set 5
- Output of C++ Program | Set 6
- Output of C Program | Set 21
- Output of C++ Program | Set 7
- Output of C++ Program | Set 9
- Output of C Program | Set 22
- Output of Java Program | Set 1
- Output of Java Program | Set 2
- Output of C++ Program | Set 10
- Output of C Program | Set 23
- Output of Java Program | Set 3
- Output of C Program | Set 24

