Unsolved : Syntax
-
Hi all in below code i am confused with :Animal(age) , why did we use it , without this error comes
#include<iostream>
using namespace std;// Your code goes here
class Animal
{public:
inline Animal(int age)
{
this->itsAge = age;
}inline virtual void Eat()
{
std::operator<<(std::cout, "Animal eats food").operator<<(std::endl);
}inline virtual int get_Age()
{
return this->itsAge;
}protected:
int itsAge;
public:
};class Dog : public Animal
{public:
inline Dog(int age)
: Animal(age)
{
}inline virtual void Eat()
{
std::operator<<(std::cout, "Dog eats meat").operator<<(std::endl);
}inline virtual int get_Age()
{
return /* static_cast<Animal *>(this)-> */ itsAge;
}};
class Cat : public Animal
{public:
inline Cat(int age)
: Animal(age)
{
}inline virtual void Eat()
{
std::operator<<(std::cout, "Cat eats meat").operator<<(std::endl);
}inline virtual int get_Age()
{
return /* static_cast<Animal *>(this)-> */ itsAge;
}};
int main()
{
Animal * a;
Dog dg = Dog(8);
Cat ct = Cat(3);
a = static_cast<Animal *>(&dg);
a->Eat();
std::operator<<(std::cout, "Dog's age is: ").operator<<(a->get_Age()).operator<<(std::endl);
a = static_cast<Animal *>(&ct);
a->Eat();
std::operator<<(std::cout, "Cat's age is: ").operator<<(a->get_Age()).operator<<(std::endl);
return 0;
} -
Please format your code with code tags so everyone can read it.
-
:Animal(age)
As @Christian-Ehrlicher says about readable code tags, please. Which
: Animal(age)
, you mean ininline Dog(int age) : Animal(age)
? So that constructor is calling the base
Animal
constructor passing in theage
it received? My knowledge of C++ is not perfect :), but without that wouldn't it look for a base constructor of plainAnimal()
, which does not exist?