Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A list containing objects of two different classes in C++

Tags:

c++

object

list

I feel more fluent in Java than C++ so I will try to explain what I want to "transport" in a few words. In Java you could create an ArrayList containing objects of 2 or more classes that one of them inherited from another. Let me illustrate. Let's say we have:

class Vehicle
{
...
}

class Car extends Vehicle
{
...
}

You could then do something like that Car a = new Vehicle ([arguments]); And then you could add objects of both Vehicle and Car to the same ArrayList created as following:

ArrayList ar = new ArrayList<Car>();

Now to my problem, in C++ I have manually written the code to create a simple linked list. Each node of this list is described below:

struct clientListNode
{
    vip* cust;
    struct clientListNode* next;
};

vip is another class which is derived from customer.Is there any way to allow my list to accept both objects of vip class and customer class?

like image 498
Theocharis K. Avatar asked Dec 04 '25 07:12

Theocharis K.


2 Answers

Polymorphism works the other way. You can use a customer* pointer to point to a vip object, but not the other way. (This is related to the Liskov-substitution principle.)

So if you had a customer* in your clientListNode class, it would accept both vip* and customer* pointers.

However, I don't think you should reinvent the wheel and implement a linked list from the ground. You should look into the STL (Standard Template Library) which already has solutions for problems like this. For instance, it already has an implementation of the linked list, std::list.

You have to template std::list with the base type you'd like to use it with, but it is important that you cannot use the type directly as a value (std::list<cust>), because that would physically store cust instances in memory, in which you cannot fit the more specific vip type (slicing would occur).
Instead you have to use some kind of handle as the template parameter, you can use a native pointer (std::list<cust*>), but that way you have to manage memory deallocation, or - more preferably - you can use a smart pointer, like shared_ptr (std::list<std::shared_ptr<cust>>), that way the created objects are going to get destroyed automatically.

like image 93
Mark Vincze Avatar answered Dec 07 '25 00:12

Mark Vincze


I doubt you could make Car = new Vehicle even in java, but the other way around makes sense.

What you're after is called "polymorphic collection". C++ standard lib does not have one out of the box, but you can approximate it with a collection of shared_ptr<Vehicle> s or unique_ptr<Vehicle> s. The former would fork very close to a java equivalent.

3rd party libraries may have ready to use polymorphic collections, you can use the term for search.

like image 43
Balog Pal Avatar answered Dec 06 '25 23:12

Balog Pal