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.