C++ Single inheritance

Single inheritance: When a only one class is derived from an existing base class is called single inheritance. Single inheritance is only possible if there are two classes which are inherit with each others. The new class is called DERIVED Class and an existing class is called BASE Class.

 

Syntax:

class base_class_name

{

private:

…………….

public:

…………….

protected:

…………….

};

class derived_class_name : public base_class_name

{

private:

……………

public:

……………

protected:

……………

};

Program:

/*PROGRAM TO IMPLEMENT SINGLE LEVEL INHERITANCE BY USING CONSTRUCTOR AND DESTRUCTOR IN BOTH CLASSES*/

#include<conio.h>

#include<iostream.h>

#include<stdio.h>

class base

{

char name[10];

int roll_no;

public:

base()

{

cout<<“Enter name: “;

gets(name);

cout<<“Enter roll number: “;

cin>>roll_no;

}

void show1()

{

cout<<“Name of the student is: “<<name<<endl;

cout<<“Roll number of the student is:

“<<roll_no<<endl;

}

~base()

{

cout<<“Destructor of base class is executed”<<endl;

}

};

class derived:public base

{

int marks;

public:

derived():base()

{

cout<<“Enter marks: “;

cin>>marks;

}

void show2()

{

cout<<“Marks of the student are: “<<marks<<endl;

}

~derived()

{

cout<<“Destructor of derived class is executed”<<endl;

}

};

void main()

{

clrscr();

{

derived d1;

d1.show1();

d1.show2();

}

getch();

}

Leave a Reply

Your email address will not be published. Required fields are marked *