Question

I have the following piece of code.

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

class B : public A {
public:
  void bar() { /* Do something */ }
}

void B::A::foo() {
   bar();
   // Do something else
}

When I try to compile this... I get an error saying it could not find bar(). Is this not the right way to instantiate the purely virtual function?

use of undeclared identifier 'bar'
Was it helpful?

Solution

void B::A::foo() doesn't make much sense. It looks like you mean to implement foo() in B, for which you need to declare it in B's class declaration, and then implement it:

class B : public A {
public:
  void foo();
  void bar() { /* Do something */ }
};

void B::foo() {
   bar();
   // Do something else
}

OTHER TIPS

Your code will not compile for a few reasons:

class A 
{
public: 
  virtual void foo() = 0; // this defining a pure virtual function - making A an abstract class
}; // missing ; here

class B : public A 
{
public:
  void bar() { /* Do something */ }
  // you never implement foo, making B another abstract class
}; // again with the ;

void B::A::foo() // this line makes no sense
{
   bar();
   // Do something else
}

I believe what you are trying to do is the following

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

class B : public A 
{
public:
    virtual void foo() { bar(); } // override A::foo
    void bar() { /* Do something */ }
};

If you are going to override a function, you must declare it as overridden. If you derive a class from an abstract base class and do not implement its functions, your derived class is also an abstract base class. Before you can instantiate any class, all of its functions must be non-abstract.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top