Why can't call a base member function from a object of sub class???

A

Albright

Code as bellow:

#include <stdio.h>
#include <string.h>

class A
{
public:
void print(char *s)
{
printf("%s\n", s);
}
};

class B : public A
{
public:
void print(int i)
{
printf("%d\n", i);
}
};

int main()
{
B b;
b.print("hello"); //Has complile error here, it indicates that b
invoke B::print() but not A::print, I want to know why.

return 0;
}

In this sample, if print(char *s) is defined in class B, it's OK, but
if in A, it's not.
Why these two functions are NOT overloaded between base class and sub
class?
 
A

Alf P. Steinbach

* Albright:
Code as bellow:

#include <stdio.h>
#include <string.h>

class A
{
public:
void print(char *s)
{
printf("%s\n", s);
}
};

class B : public A
{
public:
void print(int i)
{
printf("%d\n", i);
}
};

int main()
{
B b;
b.print("hello"); //Has complile error here, it indicates that b
invoke B::print() but not A::print, I want to know why.

return 0;
}

In this sample, if print(char *s) is defined in class B, it's OK, but
if in A, it's not.
Why these two functions are NOT overloaded between base class and sub
class?

This is a FAQ (Frequently Asked Question).

See the FAQ item titled "What's the meaning of, Warning: Derived::f(char) hides
Base::f(double)?", currently item 23.9 and available at e.g. <url:
http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.9>, plus
at a host of mirror sites.

It's often a good idea to check the FAQ.


Cheers & hth.,

- Alf
 
A

Alf P. Steinbach

* Albright:
But Why the C++ standard has this rule?

Hm, properly that question belongs in [comp.std.c++]; here in [comp.lang.c++] we
mostly only deal with the language as-is.

However...

If C++ didn't have this rule it would have to have the opposite rule, at least
for this case, i.e. no hiding. That would be a different trade-off with its own
problems. For example, in that case adding a name in a base class could silently
(or more visibly) affect code using an existing derived class, requiring fixing
all the derived classes -- pretty hopeless when your class is in a library
used by many, and the classes to be fixed are the many's derived classes.

The rule that was adopted avoids e.g. that problem, at the cost of that rule
being somewhat counter intuitive, and generating a Frequently Asked Question.

A good textbook should explain this, but I don't know whether they do.


Cheers & hth.,

- Alf
 

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,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top