0% found this document useful (0 votes)
15 views

Constructors in C M M

Uploaded by

Sushma SJ
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Constructors in C M M

Uploaded by

Sushma SJ
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Constructors in c++

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 ():

class MyClass { // The class


public: // Access specifier
MyClass() { // Constructor
cout << "Hello World!";
}
};
int main() {
MyClass myObj; // Create an object of MyClass (this will call the constructor)
return 0;
}
#include <iostream>
using namespace std;
cin >> name;
// Class definition
cout << "Enter the Fee:";
class student
cin >> fee;
{
}
int rno;
char name[50];
void display()
double fee;
{
public:
cout << endl << rno << "\t" << name << "\t"
student()
<< fee;
{
}
// Constructor within the class
};
cout << "Enter the RollNo:";
cin >> rno;
int main()
cout << "Enter the Name:";
{
cin >> name;
student s;
cout << "Enter the Fee:";
s.display();
cin >> fee; return 0;
}
#include <iostream>
cin >> name;
using namespace std;
cout << "Enter the Fee:";
// Class definition
cin >> fee;
class student
}
{
int rno; void student::display()
char name[50]; {
double fee; cout << endl << rno << "\t" << name << "\t"
public: << fee;
student(); }
void display();
}; int main()
student::student() {
{ student s;
// Constructor outside the class s.display();
cout << "Enter the RollNo:"; return 0;
cin >> rno; }
Multilevel inheritance
#include <iostream> // first sub_class derived from class
using namespace std; vehicle

// base class// base class


class fourWheeler : public Vehicle {
class Vehicle {
public: public:
Vehicle() { cout << "This is a Vehicle\n"; } fourWheeler()
}; {
class Vehicle {
public:
cout << "4 Wheeler Vehicles\n";
Vehicle() { cout << "This is a Vehicle\n"; } }
}; };
// sub class derived from the derived base
//class fourWheeler int main()
class Car : public fourWheeler {
{ // Creating object of sub class will
public: // invoke the constructor of
base //classes.
Car()
{ Car obj;
cout << "This 4 Wheeler Vehicle is a Car\n"; return 0;
} }
};
Hierarchial inheritance

#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;
}

You might also like