I have the following snippet of code:
const int DATE_LENGTH = 6;
class BaseClass {
protected:
int date[DATE_LENGTH];
int year;
public:
BaseClass(){}
BaseClass(int *d) {
for (int i = 0; i < DATE_LENGTH; i++) { date[i] = d[i];}
year = 1900 + date[4] * 10 + date[5];
}
void printYear() {
cout << year << endl;
}
};
class DerivedClass : public BaseClass {
public:
DerivedClass() {}
void printYear() {
cout << year << endl;
}
};
int main(int argc, char *argv[]) {
int dob[] = {1, 6, 1, 0, 9, 0};
BaseClass base(dob);
base.printYear(); // prints 1990
DerivedClass derived;
derived.printYear(); // prints 1439156608
}
I'm having trouble understanding why the output from printYear()
in my derived class is outputting junk. Am I missing something very obvious?
Any help would be appreciated!
The default constructor of class BaseClass
BaseClass(){}
does not initislize data members date
and year
This default constructor is called by the default constructor of class DerivedClass
when you create object derived
DerivedClass derived;
So these data members have arbitrary values and your program has undefined behaviour.
Change the derived class the following way
class DerivedClass : public BaseClass {
public:
using BaseClass::BaseClass;
DerivedClass() {}
void printYear() {
cout << year << endl;
}
};
and create object derived as
DerivedClass derived( dob );
Or instead of the using declaration you can yourself explicitly define a constructor in class DerivedClass that has one parameter of type int *
and calls the corresponding constructor of the base class. For example
class DerivedClass : public BaseClass {
public:
DerivedClass() {}
DerivedClass( int *d ) : BaseClass( d ) {}
void printYear() {
cout << year << endl;
}
};
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments