problem about virtual method hiding method of baseclass

I write a base class with a method being virtual.
But the problem occurs when I need a different signature with the method in the derived class:

1
2
3
4
5
6
7
8
9
class baseclass{
public:
	virtual void bind(int i){}
};

class derived : public baseclass{
public:
	virtual void bind(const char* i){}
};


When I try to use a pointer of baseclass points to the object of the derived class, compiler complains incompatible.

1
2
3
4
baseclass* p;
derived x;
p=&x;
p->bind("hihihi");


What should I do in a proper way.
That's something you can't do in C++. The implementation of objects doesn't support that; and that's the way you end up hiding functions. C++11 has a new keyword to warn you of this pattern.

It's back to the drawing board with your object design and think about what it means to bind to a different type, and either support that in your hierarchy or specialise it a specific type with a new method.
Hi lays.

Yes it not allowed in c++ to write function with same name with different in prototype in derived class.
e.g.
<code>virtual void bind(const char* i){}</code>

Because , while executing this line -
<code>p->bind("hihihi");</code>

here pointer pointing object of derived class.
and derived class should have two functions with name "bind", but compiler not able to use it.

so that error is come.

To resolve it you should mention base class method in base class with "using" keyword.
<code>
class derived : public baseclass{
public:
using baseclass::bind; //this must write
virtual void bind(const char* i){}
};
</code>

now compiler can resolve the following call :
<code>p->bind("hihihi");</code>
No, it can not for this. The baseclass has only bind(int) and baseclass * p accepts what the baseclass has *. You can call both bind(int) and bind(const char *), only when you use a derived object directly.

* Renaming method:
1
2
3
4
5
6
7
8
9
class baseclass{
public:
	virtual void bind(int i){}
};

class derived : public baseclass{
public:
	virtual void foo(const char* i){}
};

Will fail too:
1
2
3
4
5
baseclass* p;
derived x;
p = &x;

p->foo("hihihi"); // error: baseclass has no foo(const char*) 


Therefore, if one has to use polymorphism, one has to touch base:
1
2
3
4
5
6
7
8
9
10
class baseclass{
public:
	virtual void bind(int i){}
	virtual void bind(const char* i){}
};

class derived : public baseclass{
public:
	virtual void foo(const char* i){} // override
};


There is an alternative though:
1
2
3
4
5
6
7
baseclass* p;
derived x;
p = &x;

if ( auto d = dynamic_cast<derived *>( p ) ) {
  d->foo("hihihi");
}
Last edited on
thanks all!
Registered users can post here. Sign in or register to post.