CPP

Defining Derived Classes

  • A derived class is defined by specifying it relationship with the base class in addition to its own details.

Syntax:


class derived-class-name : visibility-mode base-class-name
{
	//members of derived class
}

Here,

  • class is the required keyword,
  • derived-class-name is the name given to the derived class,
  • base-class-name is the name given to the base class,
  • : (colon) indicates that the derived-class-name is derived from the base-class-name,
    visibility-mode is optional and, if present, may be either private or public.
  • The default visibility-mode is private.
  • Visibility mode specifies whether the features of the base class are privately derived or publicly derived.

Example:


class Shape
{
protected:
	float width, height;
public:
	void set_data (float a, float b)
	{
		width = a;
		height = b;
	}
};

class Rectangle: public Shape
{
public:
	float area ()
	{
		return (width * height);
	}
};

class Triangle: public Shape
{
public:
	float area ()
	{
		return (width * height / 2);
	}
};

void main ()
{
	Rectangle rect;
	Triangle tri;
	rect.set_data (5,3);
	tri.set_data (2,5);
	cout << rect.area() << endl;
	cout << tri.area() << endl;
	getch();
}

Output:

15
5

other_Description_add_here




Subscribe us on Youtube

Share This Page on


Ask Question