I've written two class. In Basic class I have attribute age, which is dynamically allocated. I try to use it in class Dog. The code executes but it gives me output:
mammal create
dog create
how
2
dog delete
mammal delete
munmap_chunk(): invalid pointer
Aborted (core dumped)
What is the problem with my code, how should I change it to not have problem with pointer.
Here is my code:
#include <iostream>
class Mammal
{
public:
Mammal(int nAge);
~Mammal();
int getAge();
void setAge(int nAge);
private:
int *age;
};
Mammal::Mammal(int nAge)
{
int *age = new int;
age = &nAge;
std::cout<<"mammal create \n";
}
Mammal::~Mammal()
{
std::cout<<"mammal delete \n";
delete age;
}
int Mammal::getAge()
{
return *age;
}
void Mammal::setAge(int nAge)
{
age = &nAge;
}
class Dog : public Mammal
{
public:
Dog();
~Dog();
void getVoice();
};
Dog::Dog ()
{
std::cout << "dog create \n";
}
Dog::~Dog()
{
std::cout<<"dog delete \n";
}
void Dog::getVoice()
{
std::cout<<"how \n";
}
int main()
{
Dog* dog = new Dog;
dog -> getVoice();
dog -> setAge(2);
std::cout<<dog-> getAge()<<"\n";
delete dog;
}
Summary I'd like to understand how memory allocation work with inheritance.