[c++] Can you string objects from different classes that inherit the same class like an array?

Asked 2 years ago, Updated 2 years ago, 33 views

This class is A B, C, D are inherited And the objects of B, C, and D Can you tie it up like an array? arr[0]=B object arr[1]=C object arr[2]=D object Is it possible to access the index in this way?

c++표준

2022-09-22 19:28

2 Answers

I'm going to create an array of pointers for Class A It's upcasting the objects of B, C, and D, so it comes out the way you want it Is it okay to use it like this?


2022-09-22 19:28

To manage inherited classes from one array, you can convert them to parent types.

#include <iostream>
#include <memory>

struct A {
    virtual ~A() {}
    virtual void print() { std::cout << "A" << std::endl; }
};
struct B : public A { 
    void print() { std::cout << "B" << std::endl; }
};
struct C : public A {
    void print() { std::cout << "C" << std::endl; }
};

int main() {
    A* array[] = {
        new B
        , , new C
    };

    for (std::size_t i = 0, size = sizeof(array) / sizeof(array[0]); i < size; ++i)
        array[i]->print();

    for (std::size_t i = 0, size = sizeof(array) / sizeof(array[0]); i < size; ++i)
        delete array[i];

    return 0;
}

This method is inconvenient because you have to manage the memory yourself. If you apply the smart pointer here, it is as follows.

#include <iostream>
#include <memory>

struct A {
    virtual ~A() {}
    virtual void print() { std::cout << "A" << std::endl; }
};
struct B : public A { 
    void print() { std::cout << "B" << std::endl; }
};
struct C : public A {
    void print() { std::cout << "C" << std::endl; }
};

int main() {
    std::unique_ptr<A> array[] = {
        std::unique_ptr<B>(new B)
        , , std::unique_ptr<C>(new C)
    };

    for (std::size_t i = 0, size = sizeof(array) / sizeof(array[0]); i < size; ++i)
        array[i]->print();

    return 0;
}


2022-09-22 19:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.