Providing definition of (base) nested in derived - works unexpectedly...

W

Werner

Hi All,

I've (mistakenly) done this (see below) and was surprised to
see the compiler (comeau and gcc) accept it. Is this acceptable (I
can't
see why not)?

#include <iostream>
struct Base
{
struct Nested
{
void foo();
};
};

struct Derived : Base
{
};

void Derived::Nested::foo()
{
std::cout << "foo()";
}

int main()
{
Base::Nested n;
n.foo();
}

Kind regards,

Werner
 
V

Victor Bazarov

I've (mistakenly) done this (see below) and was surprised to
see the compiler (comeau and gcc) accept it. Is this acceptable (I
can't
see why not)?
Yes.

#include<iostream>
struct Base
{
struct Nested
{
void foo();
};
};

struct Derived : Base
{
};

void Derived::Nested::foo()
{
std::cout<< "foo()";
}

int main()
{
Base::Nested n;
n.foo();
}

It works because every definition (like your definition of
'Nested::foo') starts with a declaration until you open the curly brace
instead of putting a semicolon there. The declaration is a duplicate
(since the function has already been declared in the 'Nested' class
definition) and the compiler knows that because it does name lookup when
it sees "Derived". It looks up the "final" token in that name ('foo')
and determines that you are referring to 'Base::Nested::foo' by means of
the Base's derived class. Try making 'Nested' private and you won't be
able to compile (methinks).

V
 

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,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top