You can utilize the class code in CT 2024.12 to generate std::shared_ptr. The order of creation is as follows.
- Generate pointer objects with classcode
- Generate std::shared_ptr objects with the pointer object created in 1.
Example
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class Animal {
public:
// Pure virtual function
virtual void speak() const = 0;
virtual ~Animal() {}
};
class Dog : public Animal {
public:
void speak() const override {
std::cout << “Woof!” << std::endl;
}
};
class Cat : public Animal {
public:
void speak() const override {
std::cout << “Meow!” << std::endl;
}
};
class AnimalShelter {
public:
~AnimalShelter() {
}
void addAnimal(std::shared_ptr<Animal> animal) {
animal->speak();
animals.push_back(animal.get());
}
void makeAllSpeak() const {
for (size_t i = 0; i < animals.size(); ++i) {
animals[i]->speak();
}
}
void makeAnomyAnimal() {
std::shared_ptr<Animal> a = std::make_shared<Cat>();
a->speak();
}
} private:
std::vector<Animal*> animals;
}
int main() {
AnimalShelter shelter;
shelter.makeAnomyAnimal();
return 0;
}
Use in [User code].
The test code of addAnimal
is failing to generate the std::shared_ptr object properly and is throwing a signaled error.
- Create a class factory code for the Animal class in the [Class Factory View].
- Convert
Animal *
from 1. to a std::shared_ptr object.
Use in [Stub View].
Need more help with this?
Don’t hesitate to contact us here.