C++ | Introduction to inheritance

Introduction

This is a tutorial for inheritance in c++. The program is given below that uses inheritance to calculate total marks. The program is extendable. Go enjoy the program. Lets begin……

Program for inheritance

#include<iostream.h>
#include<conio.h>
//declare one class
class one
{
public:
int rno;
char name[30];
void getdata(void)
{
cout<<“Enter rno and name”<<endl;
cin>>rno>>name;
}
};
//declare class two
class two:public one
{
int s1,s2,s3,tot;
public:
void getmarks(void)
{
cout<<“Enter three subject marks”<<endl;
cin>>s1>>s2>>s3;
tot=s1+s2+s3;
}
void print(void)
{
cout<<“Rno :”<<rno<<endl;
cout<<“Name :”<<name<<endl;
cout<<“S1 :”<<s1<<endl;
cout<<“S2 :”<<s2<<endl;
cout<<“S3 :”<<s3<<endl;
cout<<“Total:”<<tot<<endl;
}
};

void main()
{
//clear the screen.
clrscr();
//declare x as class.
two x;
//Call functions
x.getdata();
x.getmarks();
x.print();
//get character
getch();
}

Output

Enter rno and name
1
abc
Enter three subject marks
99
100
100
Rno : 1
Name : abc
S1: 99
S2 : 100
S3 : 100
Total:299

How it works

  1. You enter the data
  2. Total is calculated and printed along with given data.

Extending it

The program can be extended by using the concept in any program.

  • Remember this is a basic part of c++ which can be used in any program….

Explanation.

  1. Include ‘iostream.h’ and ‘conio.h’.
  2. Add parent class.
  3. Add child class.
  4. Add void main.
  5. Start program by first clearing the screen.
  6. Delcare class.
  7. Call functions.

At the end

You learnt creating the C++ program for inheritance in c++. So now enjoy the program.

Please comment on the post and share it.
And like it if you liked.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s