smwikipedia
smwikipedia

Reputation: 64205

Don't understand the const method declaration

Too much C# and too little C++ makes my mind dizzy... Could anyone remind me what this c++ declaration means? Specifically, the ending "const". Many thanks.

protected:
     virtual ostream & print(ostream & os) const

Upvotes: 5

Views: 506

Answers (4)

Daniel Vassallo
Daniel Vassallo

Reputation: 344291

A const method will simply receive a const this pointer.

In this case the this pointer will be of the const ThisClass* const type instead of the usual ThisClass* const type.

This means that member variables cannot be modified from inside a const method. Not even non-const methods can be called from such a method. However a member variable may be declared as mutable, in which case this restriction will not apply to it.

Therefore when you have a const object, the only methods that the compiler will let you call are those marked safe by the const keyword.

Upvotes: 10

f4.
f4.

Reputation: 3852

You're declaring a protected virtual method named print which takes as a parameter a reference to an ostream and returns a reference to an ostream.

The const keyword means the method won't be able to alter the state of the object, the this pointer will be const.

A virtual method is a method whose behavior can be overridden within an inheriting class, basically the virtual keyword gives C++ its' ability to support polymorphism.

And finally if you don't know what is a reference go there

Comming from C# I suppose you know what protected means :)

Upvotes: 1

Timo Geusch
Timo Geusch

Reputation: 24341

The const on the method declaration tells the compiler that the function is safe to call on a const object of the type the function is a member of. It also signals to the compiler that the function is not supposed to alter the state of the object and it will not be able to change any member variables that are not marked as mutable.

If you omit the const, this code will not work:

const Foo bar;
bar.print(std::cout);  // Will fail to compile unless 'print' is marked const

Upvotes: 3

Dominic Rodger
Dominic Rodger

Reputation: 99751

The ending const means that the print function shouldn't be able to change the state of any of the members of the class it is declared in (and therefore cannot call any member functions of that class which are not also declared const).

In the example below, the print function in the class Foo cannot change any of the member variables of Foo (unless they are declared mutable), and cannot call any non-const functions in Foo.

class Foo {
public:
    Foo(string value) { m_value = value; }
protected:
    ostream & print(ostream & os) const {
        m_value = string("foobar"); // won't compile
        os << m_value;
        return os;
    }
private:
    string m_value;
};

Upvotes: 4

Related Questions