Constructors in C M M
Constructors in C M M
What is a constructor?
A constructor in C++ is a special method that is automatically called when an
object of a class is created.To create a constructor, use the same name as the
class, followed by parentheses ():
#include <iostream>
using namespace std; // first sub class
class Car : public Vehicle {
// base class public:
class Vehicle { Car()
{
public:
cout << "This Vehicle is Car\
Vehicle() { cout << "This is a Vehicle\n";
n"; }
} };
};
// second sub class int main()
class Bus : public Vehicle { {
public: // Creating object of sub class will
Bus() // invoke the constructor of base
//class.
{
cout << "This Vehicle is Bus\n"; } Car obj1;
}; Bus obj2;
return 0;
}