it is used to define relationship between two class,
which a child class occurs all the properties and behaviours of a parent class.
Provides code reusability.
Ex: in my framework I have a TestBase class which I store
all my reusable code and methods. My test execution classes and
elements classes will extend the TestBase in order to reuse the code.
class left {
public:
void foo();
};
class right {
public:
void foo();
};
class bottom : public left, public right {
public:
void foo()
{
//base::foo();// ambiguous
left::foo();
right::foo();
// and when foo() is not called for 'this':
bottom b;
b.left::foo(); // calls b.foo() from 'left'
b.right::foo(); // call b.foo() from 'right'
}
};
class Print2D
{
public int X { get; set; }
public int Y { get; set; }
public Print2D(int y,int x)
{
X = x;
Y = y;
Console.WriteLine("2D");
}
public void Printing2D()
{
Console.WriteLine("X= "+X);
Console.WriteLine("Y= "+Y);
}
}
class Print3D:Print2D
{
public int X { get; set; }
public int Y { get; set; }
public int Z { get; set; }
public Print3D(int x,int y,int z) : base(x,y)
{
Z = z;
Console.WriteLine("3D");
}
public void Printing3D()
{
base.Printing2D();
Console.WriteLine("Z= " + Z);
}
}
class Program
{
static void Main(string[] args)
{
Print3D p3d = new Print3D(4,5,6);
p3d.Printing3D();
}
}
// C++ Implementation to show that a derived class
// doesn’t inherit access to private data members.
// However, it does inherit a full parent object.
class A{
public:
int x;
protected:
int y;
private:
int z;
};
class B : public A{
// x is public
// y is protected
// z is not accessible from B
};
class C : protected A{
// x is protected
// y is protected
// z is not accessible from C
};
class D : private A{ // 'private' is default for classes
// x is private
// y is private
// z is not accessible from D
};
#include <iostream>
using namespace std;
// Base class
class Shape {
public:
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape {
public:
int getArea() {
return (width * height);
}
};
int main(void) {
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl;
return 0;
}