Explain default constructor and parameterized constructor with the help of program.
//C++ program to demostrate default and parameterized constructor.
#include <iostream>
using namespace std;
class MyClass
{
//Class data members
int age;
string name;
// Default constructor
public:
MyClass()
{
cout<<"Default constructor called"<<endl;
}
//Parameterized constructor
MyClass(int a, string n)
{
cout<<"Parameterized constructor called"<<endl;
age = a;
name = n;
cout<<"His name is "<<name <<"and his age is "<<age<<endl;
}
};
// Main program
int main()
{
MyClass mc;//This will call the default constructor
MyClass mc2(12, "Joe");//This will call the parameterized constructor
return 0;
}
Comments
Leave a comment