0

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?

12
  • 2
    Move the pure virtual function to A? That's the type you actually try to use polymorphically. Commented Dec 24, 2017 at 16:25
  • 3
    So don't define it in B. It won't have it. Commented Dec 24, 2017 at 16:28
  • 1
    What gave you that idea? Commented Dec 24, 2017 at 16:28
  • 2
    only for derived classes which must be concrete classes Commented Dec 24, 2017 at 16:31
  • 2
    @Jokk - No it doesn't. Any good C++ book will tell you as much. Commented Dec 24, 2017 at 16:31

2 Answers 2

2

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() 
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

"Aaarrrrrggghhh" at that C-style cast. There's no reason not to use static_cast or dynamic_cast here.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.