0
votes

I have several general questions about C++ that I was wondering if someone could answer. I'm writing a .cpp file that has the implementations for the header file my teacher is providing us. We are not allowed to modify the file. Basically, the header has declarations for a base class ship, and 4 specific types of ships. My questions are: 1) The class definition for base class ship does not have a constructor provided. Instead, it has a protected Set function that sets the values for the private data members. Does the compiler provide a default constructor? (Basically does it automatically set the private int variables equal to 1)? Because I am using the dynamic memory function new to create objects of derived classes of Ship.

2)I have the function header virtual int size(void) const = 0; inside base class ship. I want to use the size() function inside another member function to check to see if the size of a ship is valid. Would i use this->size() to do that inside the member function declaration? (I overrided the virtual function size in each specific derived class's implementation already)

Thankyou very much! Please let me know if I need to include code or be more specific. I appreciate the help.

1
1) Does the compiler provide a default constructor? It depends, but even if it did the member ints would be default initialized, i.e. garbage. 2) Well, yes, how else would you do that? - user657267
My question is, does the compiler know automatically which size() function to choose? Because I overrided the size function for each derived class. - Kevin Cheng
Your compiler won't (well not usually), virtual dispatch is a runtime feature. The "right" function will be called at runtime if the function is virtual, assuming there are no errors in your code. - user657267

1 Answers

0
votes

1) Does the compiler provide a default constructor?

Normally, yes.

(Basically does it automatically set the private int variables equal to 1)?

No. A default constructor doesn't set int members - private or otherwise - to anything. They're uninitialised and can't be read from until after they're first assigned to.

Because I am using the dynamic memory function new to create objects of derived classes of Ship.

That's not relevant to where the private int gets initialised (i.e. it still doesn't).

2)I have the function header virtual int size(void) const = 0; inside base class ship. I want to use the size() function inside another member function to check to see if the size of a ship is valid. Would i use this->size() to do that inside the member function declaration? (I overrided the virtual function size in each specific derived class's implementation already)

As a beginner, a reasonable rule of thumb is to try to call a function as simply as possible: size(). Only if that doesn't work would you try this->size(). The reasons why it might not work get complicated, but the guideline's dead simple.