SaSJo
SaSJo

Reputation: 81

c++ access derived class with a pointer from base class

The compiler keeps saying 'class A' has no member named 'foo'. I am trying to use a function from a derived class with a pointer. Here is my code:

 class A{
  .....
};

class B:public A{
     virtual void foo() = 0;
};

class C:public B{
....
public:
    void foo(){
        ....
    }
};

I have a table of A pointers named Table and when trying

Table[j]->foo()

I am getting the compiler error.

What should I do except cast?

Upvotes: 0

Views: 455

Answers (2)

Pustovalov Dmitry
Pustovalov Dmitry

Reputation: 1047

You have a compilation error because function foo is not declared in class A.

You can declare it as pure virtual in A like this:

class A {
     virtual void foo() = 0;
};

In derived classes you don't have to declare foo as explicitly virtual. If only C is a concrete class, you don't have to declare foo in class B at all.

If your example if you know that in your array of pointers to A you have only instances of class C you can explicitly cast to pointer to C but it is a sign of poor design and I don't recommend it:

static_cast<C*>(Table[j])->foo()

Upvotes: 2

SoronelHaetir
SoronelHaetir

Reputation: 15162

If you have a pointer to a base and want to access a member of the derived type you have to cast so you have a pointer to the derived type, either that or as in your case add foo() as a virtual member to the base.

class A
{ ... };
class B : public A:{
{
public:
  virtual foo() { std::cout << "B::foo" << std::endl; }
};
class C : public B
{
public:
  void foo() { std::cout << "C::foo" << std::endl;
};
...
A * arr[8];
for(int i = 0; 8>i; ++i)
  arr[i] = new C;
((B*)arr[0])->foo(); // will print "C::foo\n"

But if you added virtual void foo() = 0; to A then you could just do arr[0]->foo() and it would still print C::foo

Upvotes: 0

Related Questions