Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inherit & change a class only for a specific object at initialization?

In Java, it is possible to modify the class structure only for a specific object at it's initialization:

Car ford = new Car(){   
    public float price;  
};

Hence, the ford object gains a new attribute called price, while other cars don't.

Is there a way I can get similar functionality in C++, without making a entire subclass?

Thanks!

like image 760
Naveen Avatar asked Feb 13 '23 09:02

Naveen


2 Answers

No in C++ you can not do it the way mentioned by you. You can use anonymous classes to do meet your requirement.

class car {
public:
    void test() { cout << "test" << endl; }
};

int main() {
    struct : public car { int price; } fordcar;
    fordcar.test();
    return 0;
}

Live code

like image 174
Mohit Jain Avatar answered Feb 15 '23 12:02

Mohit Jain


I don't think this is possible in C++, at least the same way as Java does. But, you can use the decorator pattern with a bit more code.

like image 33
Gall Avatar answered Feb 15 '23 12:02

Gall