constness and inheritance

S

sndive

struct A {
virtual int foo(const int bar);
};

int A::foo(const int bar)
{
return 0;
}
struct B : public A {
int foo(int bar);
};
int B::foo(int bar)
{
return 1;
}

int
main()
{
A *p = new B;
const int baz=-1;
int r = p->foo(baz);
return 0;
}

here B::foo is called (tried with g++3.2.3)
i wonder if it's a problem for non elementary types in parameters
since derived function can modify the baz argument with impunity
contrary to the expectations of the caller.
Granted, B::foo could've taken bar as the const parameter
and casted to non const but there are no casts of any
kind in the program above.
 
V

Victor Bazarov

struct A {
virtual int foo(const int bar);
};

int A::foo(const int bar)
{
return 0;
}
struct B : public A {
int foo(int bar);

This 'foo' *overrides* 'A::foo' because it has exactly same type.
};
int B::foo(int bar)
{
return 1;
}

int
main()
{
A *p = new B;
const int baz=-1;
int r = p->foo(baz);
return 0;
}

here B::foo is called (tried with g++3.2.3)

As it bloody well should.
i wonder if it's a problem for non elementary types in parameters
since derived function can modify the baz argument with impunity
contrary to the expectations of the caller.

Top-level const qualifiers are ignored in the function declaration
as far as type matching is concerned. In your program 'B::foo'
and 'A::foo' have *exactly same* type.
Granted, B::foo could've taken bar as the const parameter
and casted to non const but there are no casts of any
kind in the program above.

The top-level 'const' doesn't matter.

V
 
J

James Kanze

struct A {
virtual int foo(const int bar);
};
int A::foo(const int bar)
{
return 0;}
struct B : public A {
int foo(int bar);};
int B::foo(int bar)
{
return 1;
}
int
main()
{
A *p = new B;
const int baz=-1;
int r = p->foo(baz);
return 0;
}
here B::foo is called (tried with g++3.2.3)

Correct. Top level const in a function argument is ignored in
function types.
i wonder if it's a problem for non elementary types in parameters
since derived function can modify the baz argument with impunity
contrary to the expectations of the caller.

What expectations of the caller? All the caller can expect is
never to see the parameter. It's call by copy, remember.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top