NZSteve NZSteve - 1 year ago 94
C++ Question

Child Class constructor using private member

I have multiple child classes extending the base class (Media).
When I call the child classses constructor, I am not able to use the private member mBookLateFee's value to do some calculations .. it appears to be using the default 0.0 and not the members contents.
However, if I put the actual value of 1.25 in there it works..

When constructed can the object not initialize from a child classes member?

class Media {

private :
string mCallNumber;

string mStatus;
string mTitle;
string mType;
int mDaysOverDue = 0;
double mDailyLateFee = 0.0;
double mTotalLateFees = 0.0;

Media(string status, string title, int days=0, string callNum="", string type="", double fee=0.0) : mStatus(status),
mTitle(title), mDaysOverDue(days), mCallNumber(callNum), mType(type), mDailyLateFee(fee) {};
void setCallNo(string newCallNum);
string getCallNo();
void setHowLate(int numDays);
int getDaysOverDue();
virtual void print();
virtual double getFees() = 0;


class Book : public Media {
double mBookLateFee = 1.25;

string mAuthor;
int mNumPages;

Book(string status, string title, int days, string callNum, string author, int pages=0) :
Media(status, title, days, callNum, "Book", mBookLateFee), mAuthor(author), mNumPages(pages){
mTotalLateFees = mDaysOverDue * mDailyLateFee;
double getFees() { return mTotalLateFees;}
void print();


Answer Source

The superclass, the parent class, gets constructed before the child class.

When your child class invokes the superclass's, the parent class's constructor, the child class has not been constructed yet. It's mBooklateFee is not yet constructed.

In a manner of speaking, it does not exist yet. Hence, you cannot use it in order to invoke the parent class's constructor.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download