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!
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With