1

I am new to C++, but I was under the impression that virtual in C++ was the equivalent of abstract in Java. I have the following:

//A.h
class A {
public:
    void method();
protected:
    virtual void helper();
}

With the following cpp:

//A.cpp
#include "A.h"
void A::methodA() {
    //do stuff
    helper();
}

Then here's the derived class:

//B.h
#include "A.h"
class B: public A{
private:
    void helper2();
}

and the following derived cpp:

//B.cpp
#include "B.h"

void B::helper2() {
    //do some stuff
} 

void A::helper() {
    helper2();
}

However, the compiler does not seem to like that I am calling the helper2 method defined in the derived class, within a virtual method defined in the super class. It gives the error "error: ‘helper2’ was not declared in this scope". Is this not how I am supposed to use virtual methods?

Btw I can't use the keyword override.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
user3517454
  • 217
  • 2
  • 11

1 Answers1

0

[...] the compiler does not seem to like that I am calling the helper2 method defined in the derived class, within a virtual method defined in the super class. It gives the error "error: ‘helper2’ was not declared in this scope".

The error has nothing to do with the function being virtual. You can't call a derived class method from a base class. Methods declared in a derived simply don't exist in the base class.


Moreover, your assumption that virtual functions are the same as abstract functions is not true. They're not the same.

The confusing thing is that in Java, all non-static methods are virtual by default. In C++ you have to explicitly declare them virtual when needed.


Also, you should be defining all member functions of A in either A.cpp or A.h, right now you're defining A::helper in B.cpp.

Community
  • 1
  • 1
Emil Laine
  • 41,598
  • 9
  • 101
  • 157
  • Hm how would I go about accomplishing something similar to abstract then? Where you declare a function abstract in the base class, and defining them in the derived class allows you to call other methods of the derived class that is not in the base class within it? – user3517454 Mar 05 '15 at 06:18
  • I got it! I thought the fact that I cannot use override meant that the compiler would not be able to choose which method to use (the one in super vs derived), but that does not seem to be the case, if I set the virtual function declaration equal to 0 in the base. – user3517454 Mar 05 '15 at 06:30
  • Yes, [`override` just checks that it really is a function override](http://stackoverflow.com/q/13880205/3425536). – Emil Laine Mar 05 '15 at 06:33