Setting a base class property in a derived constructor

I am working through some practice problems for an intro C++ course.
In one, we must create a derived class MoneyGift, which derives from a base class Money. Money has two properties, a string name and a double value. String has no setter and can only be set with a constructor (at the time of instantiation).

MoneyGift must, in its constructor, set the name to "Money" for all its objects.

I am trying to come up with a variety of ways to do this, but so far I can only find one option. This involves calling the base constructor and passing in a set value for the name.

My question: are there any other ways to do this that don't involve calling the Base constructor?

1
2
3
4
5
  class MoneyGift :public Gift
{
public:
	MoneyGift(double newValue) : Gift("Money", newValue) {}
};


Thank you!
This is the good practice way of initialising a base class from a derived class.
What you have provided is the absolute best way to do it.

If name is a private data member, this is the ONLY way you can do it.

If name is a const data member, this is the ONLY way you can do it.

If name is a public or protected, non-const data member, you could, in theory, just add name = "Money"; to the body of the MoneyGift constructor. However, even in this case, passing the argument to the base class constructor is FAR superior. Plus, this would violate your statement that
... can only be set with a constructor (at the time of instantiation).


Topic archived. No new replies allowed.