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.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
27 Dec, 2016
Like Article
Save Article