Reputation: 95
I'm new with programming with objects, and i'm learning by myself RTTI in c++, i googled about it and found a lot of examples of RTTI using animal class and mammal class, using virtual functions and dynamic_cast, so i decided to give a try to see how it works, so i wrote a little program. Here is the code:
#include <iostream>
#include<string>
#include<cstdlib>
using namespace std;
class animal
{
public:
virtual void print()const // Virtual print function
{ cout << "Unknown animal type.\n";
}
virtual ~animal(){} // Virtual destructor, discussed below
protected:
int nlegs;
string animaltype;
};
class bird: public animal
{
protected:
string name;
public:
bird(int n, string c, string nom){nlegs = n; animaltype = c; name = nom;}
void print()const
{ cout << "A " << animaltype << " has " << nlegs << " legs.\n";
}
};
class eagle : public bird
{
public:
eagle(int n, string c, string nom)
{
nlegs = n;
clase = c;
nombre = nom;
}
};
int main()
{
int count = 1;
animal* p[count];
int i;
p[0] = new bird(2,"bird","eagle");
bird* b = new bird(2,"bird","chicken")
for (i=0; i<count; ++i)
{
b = dynamic_cast<bird*>(p[i]);
}
for (i=0; i<count; ++i)
delete p[i];
}
When i try to compile it marks some errors, but one error says "eje2a.cpp: In constructor 'eagle::eagle(int, std::string, std::string)': eje2a.cpp:53:3: error: no matching function for call to 'bird::bird()'"
What does this error refers to? do i need to create a new function named bird or is other thing that i'm missing to declare?
I would greatly appreciate your help.
Thanks in advance
Upvotes: 0
Views: 201
Reputation: 1087
eagle
does not explicitly call any bird
constructor, so the default constructor is choosen (which does not exist due to your own constructor with arguments). You may fix your code with:
eagle(int n, string c, string nom)
: bird(n, c, nom)
{
}
This : bird
syntax is an initializer list, in which you can call the base classes and the members constructors (within the constructor body, they're already initialized and you can only assign values to them).
Upvotes: 4