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.