Inheritance Concept

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

INHERITANCE

1. C++ program for Single Level Inheritance.

// C++ program to explain


// Single inheritance
#include <iostream>
using namespace std;

// base class
class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};

// sub class derived from two base classes


class Car: public Vehicle{

};

// main function
int main()
{
// creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0;
}

2. C++ program for Multilevel Inheritance.

// C++ program to implement


// Multilevel Inheritance
#include <iostream>
using namespace std;

// base class
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
class fourWheeler: public Vehicle
{ public:
fourWheeler()
{
cout<<"Objects with 4 wheels are vehicles"<<endl;
}
};
// sub class derived from two base classes
class Car: public fourWheeler{
public:
Car()
{
cout<<"Car has 4 Wheels"<<endl;
}
};

// main function
int main()
{
//creating object of sub class will
//invoke the constructor of base classes
Car obj;
return 0;
}
3. C++ program for Multiple Inheritance.

// C++ program to explain


// multiple inheritance
#include <iostream>
using namespace std;

// first base class


class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
// second base class
class FourWheeler {
public:
FourWheeler()
{
cout << "This is a 4 wheeler Vehicle" << endl;
}
};

// sub class derived from two base classes


class Car: public Vehicle, public FourWheeler {

};

// main function
int main()
{
// creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0;
}
4. C++ program for demonstrating the accessibility in derived class in Inheritance.

#include <iostream>
using namespace std;
class Base {
protected :
int num = 7; //protected value
};
class Derived : public Base {
public :
void func() {
cout << "The value of num is: " << num;
}
};
int main() {
Derived obj;
obj.func();
return 0;
}

You might also like