Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I have to specify pure virtual functions in the declaration of a derived class in Visual C++?

Given the base class A and the derived class B:

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

class B : public A {
public:
  void g();
};

void B::g() {
    cout << "Yay!";
}

void B::f() {
    cout << "Argh!";
}

I get errors saying that f() is not declared in B while trying do define void B::f(). Do I have to declare f() explicitly in B? I think that if the interface changes I shouldn't have to correct the declarations in every single class deriving from it. Is there no way for B to get all the virtual functions' declarations from A automatically?

EDIT: I found an article that says the inheritance of pure virtual functions is dependent on the compiler: http://www.objectmentor.com/resources/articles/abcpvf.pdf

I'm using VC++2008, wonder if there's an option for this.

like image 396
neuviemeporte Avatar asked Dec 10 '22 16:12

neuviemeporte


2 Answers

Do I have to declare f() explicitly in B?

Yes, you have to declare in the class' definition all virtual function of any base classes that you want to override in the class. As for why: That's just the way the C++ syntax is.
Note that the virtual keyword can be omitted for the declaration of overriding virtual functions:

class base {
  virtual void f();
  virtual void g();
};

class derived : public base {
  virtual void f(); // overrides base::f()
  void g();         // overrides base::g()
};

Note: A class declaration is this: class my_class;, while this class my_class { /* ... */ }; is a class definition. There's a limited number of things you can do with a class that's only been declared, but not defined. In particular, you cannot create instances of it or call member functions.
For more about the differences between declaration and definitions see here.

Ok, for the benefit of the "declaration vs. definition" debate happening in the comments, here is a quote from the C++03 standard, 3.1/2:

A declaration is a definition unless it [...] is a class name declaration [...].

3.1/3 then gives a few examples. Amongst them:

[Example: [...]
struct S { int a; int b; }; // defines S, S::a, and S::b
[...]
struct S; // declares S
—end example]

To sum it up: The C++ standard considers struct S; to be a declaration and struct S { /*...*/ }; a definition. I consider this a strong backup of my interpretation of "declaration vs. definition" for classes in C++.

like image 85
sbi Avatar answered Jan 04 '23 23:01

sbi


Yes, in C++ you have to explicitly clarify your intention to override the behavior of a base class method by declaring (and defining) it in the derived class. If you try to provide a new implementation in derived class without declaring it in class definition it will be a compiler error.

like image 29
Naveen Avatar answered Jan 05 '23 00:01

Naveen