Hi,

I am learning inheritance and abstract base classes. I need to define an abstract base class (ABC) that provides interfaces, and a derived class (directly from the ABC) that provides the implementation. The derived class may need additional member functions and variables (both, public and private).

Using a pointer to the base class, an object of the derived class will be instantiated. Is it possible to access the additional public member functions of the object using a pointer to the base class?

I have written the following sample code :

#include <stdio.h>

using namespace std;

class base_class {
public:
  base_class() {}
  virtual ~base_class() {}
  virtual void func_1(void)=0;
  virtual void func_2(void)=0;
private:

}; // base_class

class derived_class: public base_class {
public:

  derived_class(unsigned int value) {
    y = value;
  }
  ~derived_class() {}

  void func_1(void) {
    printf("This is func_1\n");
  }

  void func_2(void) {
    printf("This is func_2\n");
  }

  void func_3(void) {
    printf("This is func_3\n");
  }

  void print_y(void) {
    printf("y = %d\n", y);
  }

private:
  unsigned int y;
}; // derived class

int main(void) {
  base_class *obj;

  obj = new derived_class (10);
  
  obj->func_1();
  obj->func_2();
  obj->func_3();
  obj->print_y();

  return 0;
}

And I get this error at compile:

g++ -o derived_class derived_class.cc
derived_class.cc: In function âint main()â:
derived_class.cc:51: error: âclass base_classâ has no member named âfunc_3â
derived_class.cc:52: error: âclass base_classâ has no member named âprint_yâ

What am I doing wrong? I have tried :

obj = reinterpret_cast<derived_class *> (new derived_class (10));

but I get the same error.

Thanks.

you need to typecast the base class pointer into a derived class pointer before it can call functions unique to the derived class. Base class knows nothing about those functions. derived_class *pDerived = reinterpret_cast<derived_class*>(obj);

int main(void) {
  base_class *obj;

  obj = new derived_class (10);
  derived_class* pDerived = reinterpret_cast<derived_class*>(obj);     
  obj->func_1();
  obj->func_2();
  pDerived->func_3();
  pDerived->print_y();

  return 0;
}
commented: Perfect! Solved my problem. +1

So a pointer to the base class CAN point to an object of a derived class, but you CANNOT access the additional members of the derived class (that are not a part of the base class) through that pointer (to the base class).

Got it.

Thanks !

Yes, and that feature is quite handy in several ways, for example when creating an array of classes all derived from the same base class.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.