I am new to classes, and I am trying to understand how constructors work when used one in another by inherited classes. So in my project I have 2 classes. For instance one being postalService:
class postalService {
private:
string address;
Date date //I used another class Date (composition)
public:
postalService();
postalService(string a, int b, int c, int d);
postalService(const postalService& p);
~postalService();
}
With constructors:
postalService::postalService():address(""), date(){
}
postalService::postalService(string a, int b, int c, int d):address(a), date(b,c,d){
}
postalService::postalService(const postalService& p) {
}
postalService::~postalService(){
}
And then another class being Letter, which is inherited by class postalService:
class letter : public postalService {
private:
bool registered_shipment;
string sender;
public:
letter();
letter(postalService& a, bool b, string c);
letter(const letter& p);
~letter();
With constructors:
letter::letter():postalService(), registered_shipment(false), sender("") {
}
letter::letter(const letter& p):postalService(p), registered_shipment(p.registered_shipment), sender(p.sender) {
}
letter::letter(postalService& a, bool b, string c):postalService(a), registered_shipment(b), sender(c){
}
letter::~letter(){
}
Now, when i try this code below if I create an object of postalService (not with default constructor) named service
and try to include it in my object letter using the following constructor: letter::letter(postalService& a, bool b, string c):postalService(a), registered_shipment(b), sender(c){
}
:
letter my_letter(service, true, "John Smith");
Every inherited variable is empty (not the same as in service
object).
I am trying to understand what is going on here. I hope I made my self clear and I apologize for such stretched out question. Thanks in advance.
You have two problems:
The postalService
copy-constructor, which you invoke in the specific letter
constructor, does nothing. That means it will not set anything.
The letter
class already is a postalService
class, that means you don't create a separate instance of the postalService
class and pass it as an argument. Because then the inherited field will be empty (you never set them in the letter
instance).
If you want to set the postalService
member variables, you need to create an appropriate constructor in the letter
class, and in its initializer list call the appropriate constructor in the postalService
class.