why this wont compile?

  • Thread starter Thread starter Gabest
  • Start date Start date
G

Gabest

---------

typedef struct {int i;} somestruct;

class A
{
public:
A() {}
bool read(char* ptr, int len);
// bool read2(char* ptr, int len); // 1.
};

class B : public A
{
public:
B() {}
bool read(somestruct* s) {return read((char*)s, (int)sizeof(*s));}
// bool read(somestruct* s) {return read2((char*)s, (int)sizeof(*s));} // 1.
// bool read(somestruct* s) {return A::read((char*)s, (int)sizeof(*s));} //
2.
};

----------

A::read was inherited and should be in scope with B::read, but the compiler
still can't find it. I have even casted the second argument to int, but it
didn't help either, hehe... If I rename A::read to A::read2 and call read2
(1), or if I call A::read(...) by specifying the scope (2) then it works,
but it is pretty inconvinient and unnecessarily looking to my opinion. I
suspect there is a standard compliance behind this, but what is the reason
disallowing this kind of code? And why is it case so different from the
following piece of (compiling) code? (please ignore that ptr is pointing to
nowhere :)

----------

typedef struct {int i;} somestruct;

bool read(char* ptr, int len);
bool read(somestruct* s) {return read((BYTE*)s, sizeof(*s));}

void somefunct()
{
char* ptr;
read(ptr, 1);
somestruct s;
read(&s);
}

----------
 
Because C++ uses "hide by name" rules instead of "hide by signature". The
definition of read in class B makes all definitions of read in base classes
hidden.

Use a "using declaration" to get the behavior you want.

class B : public A
{
public:
B() {}
using A::read;
bool read(somestruct* s) {return read((char*)s, (int)sizeof(*s));
}

Ronald Laeremans
Visual C++ team
 
Ronald Laeremans said:
Because C++ uses "hide by name" rules instead of "hide by signature". The
definition of read in class B makes all definitions of read in base classes
hidden.

Use a "using declaration" to get the behavior you want.

class B : public A
{
public:
B() {}
using A::read;
bool read(somestruct* s) {return read((char*)s, (int)sizeof(*s));
}

Ronald Laeremans
Visual C++ team

Thanks, I had absolutely no idea about this "using" keyword before! I
guess it is never late to learn something new.
 
Back
Top