1. Home
  2. Computing & Technology
  3. C / C++ / C#

Learn about C++ Classes and Objects

By , About.com Guide

5 of 9

Learn about Inheritance and Polymorphism

This example will demonstrate inheritance. This is a two class application with one class derived from another.
#include <iostream>
#include <stdio.h>

class Point
{

int x,y;
public:
Point(int atx,int aty ) ; // Constructor
inline virtual ~Point() ; // Destructor
virtual void Draw() ;
};

class Circle : public Point {

int radius;
public:
Circle(int atx,int aty,int theRadius) ;
inline virtual ~Circle() ;
virtual void Draw() ;
};


Point ::Point(int atx,int aty) {
x = atx;
y = aty;
}

inline Point::~Point ( void ) {
std::cout << "Point Destructor called\n";
}

void Point::Draw( void ) {
std::cout << "Point::Draw point at " << x << " " << y << std::endl;
}


Circle::Circle(int atx,int aty,int theRadius) : Point(atx,aty) {
radius = theRadius;
}

inline Circle::~Circle() {
std::cout << "Circle Destructor called" << std::endl;
}

void Circle::Draw( void ) {
Point::Draw() ;
std::cout << "circle::Draw point " << " Radius "<< radius << std::endl;
}

int main() {
Circle ACircle(10,10,5) ;
ACircle.Draw() ;
return 0;
}
The example has two classes Point and Circle, modelling a point and a circle. A Point has x and y coordinates. The Circle class is derived from the Point class and adds a radius. Both classes include a Draw() member function. To keep this example short the output is just text.

On the next page - Learn how Inheritance works.

Explore C / C++ / C#
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. Learn about Inheritance and Polymorphism

©2009 About.com, a part of The New York Times Company.

All rights reserved.