A sample C++ question for you to ponder

I am collecting C++ questions. And I really don't want to ask the much used what is inheritance? what is polymorphism? 

And I don't want to ctrl C and ctrl V either. So I am making up my own questions. I can see a smirk on your faces.

OK, OK. Let us see if you can predict the output of the program. Do predict without compiling and running the program please.

#include<iostream>
using namespace std;
class A
{
    int n;
public:
   A(int);
   ~A();
   void print();
 }
    A::A(int m):n(m)
   {
       cout<<"Constructor";
   }
  A::~A()
  {
     cout<<"Destructor";
  }
void A::print()
{
    cout<<m;
}

int main()
{
      A obj1(10);
      obj1.print();
      A obj2[3];
      obj2[0].print();
}

Again, I see the smirk on your face. If you say the output is
ConstructorConstructorConstructorConstructorDestructorDestructorDestructorDestructor

If you say that, now you can compile and run the program.

:)

Comments

Popular Posts