Inheritance in C++

// base.h
class base {
public:
  void f1();              // f1 cannot be overwritten
  virtual void f2();      // f2 can be overwritten
  virtual void f3() = 0;  // f3 is a pure virtual function and 
                        // must be overwritten
};
// derived.h
class derived : public base {
public:
  void f1();
  virtual void f2();
  virtual void f3();
};

Notes about derived class:

  • Relationship = “derived is a kind of base”
  • A derived class is first of all a base class.
  • A derived class can access only the protected and the public members of the base class.
  • If a class contains a pure virtual function, such a class cannot be instantiated and is called an abstract class. (e.g. base cannot be instantiated)
base* b = new derived(…);

Static type of (*b) is base.

Dynamic type of (*b) is derived.

b->f1() invokes base::f1()

b->f2() invokes derived::f2()

b->f3() invokes derived::f3()

Constructor Destructor Copy constructor Assignment operator
base::base()
{
// Initialize base members
}
virtual base::~base()
{ 
// Cleanup base members
}
base::base(const base& 
           other)
{
 ...
}
base& base::operator=
(const base& other)
{
 if (this != &other) 
 {
   ...
 }
 return *this;
}
derived::derived() 
: base()//executes first
{
// Initialize derived members
}
virtual derived::~derived()
{
// Clean-up derived
// Clean-up base
}
derived::derived
(const derived& other)
: base(other)
{
 ...
}
derived& derived::operator=
(const derived& other)
{
 if (this != &other) 
 {              
  base::operator=(other);
  ...
 }
 return *this;
}

 

Slicing => Information loss

void func(base b) { … }
derived d;
func(d);  // Invokes the copy constructor for base

Lossless ways of passing the derived class

Passing by pointer

void func(base* b) { … }
derived* d;
func(d);

Passing by reference

void func(base& b) { … }
derived d;
func(d);
This entry was posted in C++. Bookmark the permalink.

Comments are closed.