0

I am a newbie to CPP and I am practicing inheritance. I think I got something wrong with the syntax but I couldn't tell the reason.Here is part of my code:

#include<iostream>
using namespace std;

class Clown{
public:
  string name ;
  void dance();
  Clown(string s) {name = s;}


};


class CircusClown: public Clown{
public:
  string name;
  void dance();
  CircusClown(string s){name = s;}
};

I think something wrong with my inherited class.

am using Mac so there is something wrong with displaying but here is the error:

Clowns.cpp: In constructor â:
Clowns.cpp:18: error: no matching function for call to â
Clowns.cpp:8: note: candidates are: Clown::Clown(std::string)
Clowns.cpp:4: note:                 Clown::Clown(const Clown&)
Nob Wong
  • 239
  • 2
  • 5
  • 14

1 Answers1

4

When you construct the derived class, a constructor of base class must be called as well. And since your base class (Clown) doesn't provide the default constructor, the compiler doesn't know which one of the Clown's constructors should be used.

In this case, you need to call the Clown's constructor explicitly. Also avoid using namespace std; and consider passing std::string objects by const reference instead of passing by value:

class CircusClown : public Clown {
public:
    std::string name;
    CircusClown(const std::string& s) : Clown(s), name(s) { }
};

For more info, see What are the rules for calling the superclass constructor?.

Community
  • 1
  • 1
LihO
  • 41,190
  • 11
  • 99
  • 167
  • but still inherited class should take input by themselves so according to what you are doing here it doesn't take any argument right when initiating? – Nob Wong Sep 21 '13 at 20:59
  • @NobWong: `class CircusClown` from the code I posted in my answer can be used like this: `CircusClown krusty("Krusty");`. – LihO Sep 21 '13 at 21:03
  • OK I think i am just not familiar with the syntax. Thanks! – Nob Wong Sep 21 '13 at 21:05