Reputation: 763
I have 3 classes. Let's call them Class A, class B and class C.
Class C inherits from Class B and class B inherits from class A. (There are other classes as well which inherit from class B)
EG
classC -> classB -> classA
classD -> classB -> classA
classE -> classB -> classA
I want to create a class C object.
Class A has a variable 'name' Class B has a variable 'choice'
I want the constructor of class C objects to create the objects with a given name.
This is how I've done my .h files (which obviously doesn't work) These extracts are from the relevant .h files. I have a .h file and a .cpp file for each class.
class classC: public classB {
public:
classC(string name):classA(name){}
};
class classB : public classA {
public:
classB(string name);
void setChoice();
string getChoice();
protected:
string choice;
};
class classA {
public:
classA();
classA(string name);
string getName();
virtual void setChoice();
protected:
string name;
};
The extracts from the .cpp files are as follows:
ClassC **
classC::classC(string name) {}
void classC::setChoice() {
choice = "P";
}
ClassB **
classB::classB(string name):classA(name){}
string classB::getChoice(){
return choice;
}
void classB::setchoice(string newChoice){
choice = newChoice;
}
* ClassA*
classA::classA() {}
classA::classA(string aName):name(aName){}
string classA::getName() {
return name;
}
void classA::setSelection() {}
Driver:
classC* classC1 = new classC("tomato");
class1C->setChoice();
cout << "Name is " << classC1->getName() << endl;
cout << "Choice is " << classC1->getChoice() << endl;
I have a setChoice method set up as virtual as I want each class from Class C - Class Z to have their own specific setChoice function. The specifications of this project also state that this function must be declared in ClassA.
I'm getting an error stating that ClassB expects 1 argument, and none is provided.
Can somebody please point me int he right direction. I'm out of ideas.
Upvotes: 2
Views: 1055
Reputation: 19721
Your first error is that you have to define the base class before defining the derived classes.
The second problem is that you can only call the constructors of direct bases. That is, in the constructor for class C, you have to call the constructor of classB, which then can pass the argument on to classA. So the complete code would look like this:
class classA {
public:
classA();
classA(string name);
string getName();
virtual void setChoice();
protected:
string name;
};
class classB : public classA {
public:
classB(string name): classA(name){}
void setChoice();
string getChoice();
protected:
string choice;
};
class classC: public classB {
public:
classC(string name):classB(name){}
};
Upvotes: 4