Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Inheritance in C++
#include<iostream>
using namespace std;
class A //base class
{
public:
int i;
void data1(int j)
{
i=j;
cout<<"The result is: \t"<<i<<endl;
}
void display()
{
cout<<i;
}
};
class B:virtual public A //derived class
{
int x;
public:
void data2(int y)
{
x=y;
cout<<"The result is: \t"<<x<<endl;
}
void data3(int z, int x)
{
i=x;
data1(z);
}
};
class C:virtual public A
{
int k;
public:
void data4(int c)
{
k=c;
cout<<"The value of k is :\t"<<k<<endl;
}
};
class D:public B,public C
{
int y;
public:
void data5(int p)
{
y=p;
cout<<"The value of p is :\t"<<y<<endl;
}
};
int main()
{
D obj;
obj.i=100;
obj.display();
return 0;
}
// A can be accessed via both directions therefore we have to write virtual before inheriting ...
//Using Public
#include<iostream>
using namespace std;
class A //base class
{
int i;
public:
void data1(int j)
{
i=j;
cout<<"The result is: \t"<<i<<endl;
}
};
class B:public A //derived class
{
int x;
public:
void data2(int y)
{
x=y;
cout<<"The result is: \t"<<x<<endl;
}
};
int main()
{
//A obj1;
//obj1.data1(30);
B obj2;
obj2.data2(50);
obj2.data1(30);
return 0;
}
//Using protected
#include<iostream>
using namespace std;
class A //base class
{
protected:
int i;
public:
void data1(int j)
{
i=j;
cout<<"The result is: \t"<<i<<endl;
}
};
class B:private A //derived class
{
int x;
public:
void data2(int y)
{
x=y;
cout<<"The result is: \t"<<x<<endl;
}
void data3(int z, int x)
{
i=x;
data1(z);
}
};
int main()
{
B obj2;
obj2.data2(50);
obj2.data3(100,90);
//obj2.i=100;
return 0;
}
//Normal without inheritance
#include<iostream>
using namespace std;
class A
{
int i;
public:
void data1(int j)
{
i=j;
cout<<"The result is: "<<i<<endl;
}
};
class B
{
int x;
public:
void data2(int y)
{
x=y;
cout<<"The result is: "<<x<<endl;
}
};
int main()
{
A obj1;
obj1.data1(30);
B obj2;
obj2.data2(50);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment