26

I have a declaration in a cpp where a function is like:

virtual void funcFoo() const = 0;

I assume that can be inherited by another class if is declared explicit, but what's the difference between

virtual void funcFoo() = 0;

Is important to me improve my programming and i want to know the difference. I don't want a malfunction caused by a bad inherit.

Thanks in advance.

Vikas Patidar
  • 42,865
  • 22
  • 93
  • 106
vgonisanz
  • 11,831
  • 13
  • 78
  • 130

5 Answers5

35

The first signature means the method can be called on a const instance of a derived type. The second version cannot be called on const instances. They are different signatures, so by implementing the second, you are not implementing or overriding the first version.

struct Base {
   virtual void foo() const = 0;
};

struct Derived : Base {
   void foo() { ... } // does NOT implement the base class' foo() method.
};
Trevor Dixon
  • 23,216
  • 12
  • 72
  • 109
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • 3
    no, it's the other way around: the first function can be called on both const and non-const instances, while the 2nd only on non-const instances (I know it's complicated, I got it wrong too the first time :-) – Péter Török Apr 02 '12 at 10:09
17
virtual void funcFoo() const = 0;
// You can't change the state of the object.
// You can call this function via const objects.
// You can only call another const member functions on this object.

virtual void funcFoo() = 0;
// You can change the state of the object.
// You can't call this function via const objects.

The best tutorial or FAQ I've seen about const correctness was the C++ FAQ by parashift:
http://www.parashift.com/c++-faq-lite/const-correctness.html

zeFree
  • 2,129
  • 2
  • 31
  • 39
felipe
  • 1,212
  • 1
  • 15
  • 27
11

The difference is that the first function can be called on const objects, while the second can't. Moreover, the first function can only call other const member functions on the same object. Regarding inheritance, they behave the same way.

See also the C++ FAQ on this topic.

Péter Török
  • 114,404
  • 31
  • 268
  • 329
3

The two virtual functions have different signatures but inheriting will work the same way. The former is a const method and can only support const operations (methods) and objects.

Konrad
  • 39,751
  • 32
  • 78
  • 114
1

const methods can not change the state of the object so the

virtual void funcFoo() const = 0;

will be called in const instances of this class with the difference of

virtual void funcFoo() = 0;

which could be called only in non constant instances. Try to google for the const logic in c++. http://en.wikipedia.org/wiki/Const-correctness

AlexTheo
  • 4,004
  • 1
  • 21
  • 35