Inheritance | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Inheritance

Why this program don’t print out on the screen variables name and course when we use constructor? #include <iostream> #include <string> using namespace std; class Stu{ string name, course; public: Stu() {} Stu(string name, string course) { //parameterised consturctor this->name = name; this->course = course; } void showstud() { cout << "Name" << name << endl; cout << "Course " << course << endl; } }; class marks :public Stu { int m, p, c; public: marks(string name, string course,int m ,int p,int c) { Stu(name, course); this->m = m; this->p = p; this->c = c; } void showmarks() { cout << m << endl << p << endl<< c << endl; } }; void main() { marks ma("Ram", "Jam", 3, 4, 5); ma.showstud(); ma.showmarks(); }

14th Dec 2018, 4:13 PM
Nikola
Nikola - avatar
2 Answers
+ 2
thank you sooo much !!
14th Dec 2018, 6:53 PM
Nikola
Nikola - avatar
+ 1
the call of the base class constructor must be in the initializer-list of the constructor of the subclass: class marks :public Stu { public: marks(string name, string course,int m ,int p,int c) : Stu(name, course) { /* ......*/ } // ....... }; https://code.sololearn.com/c1lDSzhwN9nF/#cpp tip: base-class constructors that take arguments have to be called there before any members are initialized of sub-class
14th Dec 2018, 5:47 PM
MO ELomari