Constructor and Destructor in C++

Example Constructor and Destructor

#include <iostream>
 
using namespace std;
 
class MyObject{
   public:
      MyObject();   // This is the constructor declaration
      ~MyObject();  // This is the destructor: declaration
};
 
// Member functions definitions including constructor
MyObject::MyObject(void) {
   cout << "Object is being created" << endl;
}

MyObject::~MyObject(void) {
   cout << "Object is being deleted" << endl;
}
  
// Main function for the program
int main( ) {
   MyObject Obj;
   return 0;
}

Base class Parameterized Constructor in Derived class Constructor

class Base
{ int x;
  public:
  Base(int i)
  { x = i;
    cout << "Base Parameterized Constructor";
  }
};

class Derived : public Base
{ int y;
  public:
  Derived(int j) : Base(j)
  { y = j;
    cout << "Derived Parameterized Constructor";
  }
};

int main()
{
 Derived d(10) ;
 cout << d.x ;    // Output will be 10
 cout << d.y ;    // Output will be 10
}

Constructor call in Multiple Inheritance

class A : public B, public C ;
Advertisements
This entry was posted in C\C++ and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s