Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple C++ Inheritance Example, What's wrong? [duplicate]

Tags:

c++

oop

Possible Duplicate:
Function with same name but different signature in derived class

I'm trying to compile this and I can't figure out what is wrong with the code. I'm using MacOSX Snow Leopard with Xcode g++ version 4.2.1. Can someone tell me what the issue is? I think this should compile. And this is not my homework I'm a developer...at least I thought I was until I got stumped by this. I get the following error message:

error: no matching function for call to ‘Child::func(std::string&)’
note: candidates are: virtual void Child::func()

Here is the code:

#include <string>

using namespace std;

class Parent
{
public:
  Parent(){}
  virtual ~Parent(){}
  void set(string s){this->str = s;}
  virtual void func(){cout << "Parent::func(" << this->str << ")" << endl;}
  virtual void func(string& s){this->str = s; this->func();}
protected:
  string str;
};

class Child : public Parent
{
public:
  Child():Parent(){}
  virtual ~Child(){}
  virtual void func(){cout << "Child::func(" << this->str << ")" << endl;}
};

class GrandChild : public Child
{
public:
  GrandChild():Child(){}
  virtual ~GrandChild(){}
  virtual void func(){cout << "GrandChild::func(" << this->str << ")" << endl;}
};

int main(int argc, char* argv[])
{
  string a = "a";
  string b = "b";
  Child o;
  o.set(a);
  o.func();
  o.func(b);
  return 0;
}
like image 464
bantl23 Avatar asked May 17 '11 19:05

bantl23


1 Answers

The presence of Child::func() hides all overloads of Parent::func, including Parent::func(string&). You need a "using" directive:

class Child : public Parent
{
public:
  using Parent::func;
  Child():Parent(){}
  virtual ~Child(){}
  virtual void func(){cout << "Child::func(" << this->str << ")" << endl;}
};

EDIT: Or, you may specify the correct scope yourself:

int main(int argc, char* argv[])
{
  string a = "a";
  string b = "b";
  Child o;
  o.set(a);
  o.func();
  o.Parent::func(b);
  return 0;
}
like image 139
Robᵩ Avatar answered Sep 20 '22 02:09

Robᵩ