Calling identically-named parent method

S

Spoon

Hello,

Consider the following code.

$ cat foo.C
#include <cstdio>

struct A
{
int bar() { puts("A::bar()"); return 666; }
int Abar() { puts("A::bar()"); return 666; }
};

struct B : public A
{
void bar(int n) { printf("B::bar(%d)\n", n); }
};

int main()
{
B foo;
foo.bar(123);
foo.bar();
foo.A::bar();
foo.Abar();
return 0;
}

Both A and B provide a method 'bar' but the signature is different.
int bar(void) in A
void var(int) in B

I have an object of type B, and I want to call A's bar.

The ovious foo.bar() is considered a syntax error by GCC.

$ g++ -Wall -Wextra -std=c++98 -pedantic foo.C
foo.C: In function `int main()':
foo.C:18: error: no matching function for call to `B::bar()'
foo.C:11: note: candidates are: void B::bar(int)

Does this mean I either have to change the name of A's bar as in Abar,
or qualify bar as in A::bar? Are there other alternatives?

Regards.
 
R

Rahul

Hello,

Consider the following code.

$ cat foo.C
#include <cstdio>

struct A
{
int bar() { puts("A::bar()"); return 666; }
int Abar() { puts("A::bar()"); return 666; }

};

struct B : public A
{
void bar(int n) { printf("B::bar(%d)\n", n); }

};

int main()
{
B foo;
foo.bar(123);
foo.bar();
foo.A::bar();
foo.Abar();
return 0;

}

Both A and B provide a method 'bar' but the signature is different.
int bar(void) in A
void var(int) in B

I have an object of type B, and I want to call A's bar.

The ovious foo.bar() is considered a syntax error by GCC.

$ g++ -Wall -Wextra -std=c++98 -pedantic foo.C
foo.C: In function `int main()':
foo.C:18: error: no matching function for call to `B::bar()'
foo.C:11: note: candidates are: void B::bar(int)

Does this mean I either have to change the name of A's bar as in Abar,
or qualify bar as in A::bar? Are there other alternatives?

Regards.

Redefining base class member function in the derived class, hides all
the implementation of the base class members. You could use,

foo.A::bar();
 

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

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top