I created two objects from derived classes (Dog and Cat), which I assigned to one common array, which is the Animal type. Now I want to check a single element of the array to see if it is a dog. If there is, I want it to execute a method from Dog class and bark.
#include <iostream>
using namespace std;
class Animal{
public:
Animal() {}
virtual ~Animal() {}
};
class Dog : public Animal{
public:
Dog() {}
virtual ~Dog() {}
void soundOf(){
cout << "Woof woof" << endl;
}
};
class Cat : public Animal{
public:
Cat() {}
virtual ~Cat() {}
void soundOf(){
cout << "Meoow" << endl;
}
};
int main() {
Animal animals[2];
Dog dog;
Cat cat;
animals[0] = dog;
animals[1] = cat;
Animal *ptr = animals 0;
Dog* dg = dynamic_cast<Dog*>(ptr);
if(dynamic_cast<Dog*>(ptr) != nullptr){
cout << "This is a dog" << endl;
dg->soundOf();
}else if(dynamic_cast<Cat*>(ptr) != nullptr){
cout << "This is a cat" << endl;
dg->soundOf();
}
return 0;
In "if", I also used the following method
if(Dog* dg = dynamic_cast<Dog*>(ptr))
But the effect was the same. It returned NULL every time. When I wrote the same application in Java, it was enough to use "instanceof", but here I can't do it.
CodePudding user response:
Others have commented as to why you are having this issue but have not really suggested a fix. You should get into the habit of using dynamically allocated objects and ensuring they behave nicely by using std::shared_ptr and std::vector.
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class Animal
{
public:
Animal() {}
virtual void soundOf() {}
virtual ~Animal() {}
};
class Dog : public Animal
{
public:
Dog() {}
virtual ~Dog() {}
void soundOf()
{
cout << "Woof woof" << endl;
}
};
class Cat : public Animal
{
public:
Cat() {}
virtual ~Cat() {}
void soundOf()
{
cout << "Meoow" << endl;
}
};
typedef std::shared_ptr<Animal> AnimalPtr;
int main()
{
std::vector<AnimalPtr> animals;
AnimalPtr dog = std::make_shared<Dog>();
AnimalPtr cat = std::make_shared<Cat>();
animals.push_back(dog);
animals.push_back(cat);
AnimalPtr ptr = animals[0];
if (dynamic_cast<Dog *>(ptr.get()) != nullptr)
{
cout << "This is a dog" << endl;
ptr->soundOf();
}
else if (dynamic_cast<Cat *>(ptr.get()) != nullptr)
{
cout << "This is a cat" << endl;
ptr->soundOf();
}
return 0;
}
this might seem long winded but will scale much better (and provides the functionality you want)