Fihop
Fihop

Reputation: 3177

overloaded based on constness

I'm reading Essential C++. In the section 4.3, the author gives an example to explain the usage of const

class val_class {
public:
    val_class(const BigClass &v)
        : _val(v) {}

    const BigClass& val() const {return _val;}
    BigClass& val() {return _val;}
};

void example(const BigClass *pbc, BigClass &rbc)
{
    pbc->val();
    rbc.val();
}

In the above code segment, the author overloads the function val based on constness. And then the pbc->val() will invoke const instance, rbc.val() will invoke non-const instance.

The pbc is a const pointer of type BigClass. How can we guarantee that the BigClass has a member function val ? Should the BigClass be replaced with val_class in the example function?

Upvotes: 1

Views: 117

Answers (2)

AnT stands with Russia
AnT stands with Russia

Reputation: 320491

Must be this: Your Full Example

This is obviously just a typo in the book. As you figured out for yourself, the example function should look as follows

void example(const val_class *pbc, val_class &rbc)
{
    pbc->val();
    rbc.val();
}

Upvotes: 2

ForEveR
ForEveR

Reputation: 55887

Must be replaced since BigClass cannot be derived from val_class (val_class cannot store reference or const-reference to BigClass object, because code will not compilable in this case, so it can store only BigClass object and then BigClass cannot be derived from val_class because cannot store object of undeclared/non-full declared type).

Upvotes: 0

Related Questions