If I create a class with multiple variables and a constructor that initializes them. Then I create an inheritance that uses all those variables. Now in int main I only make an object from the inherited class , how can I then define the variables from the parent class and use them in the inherited class?
( I hope I made sense >.<)
#include <iostream>
#include <string>
usingnamespace std;
class question3{
public:
question3(string a, int b, int c, int d){name=a; salary=b; minions=c; weapons = d;}
question3 operator++ (){
minions++;
weapons++;
return *this;
}
question3 operator-(question3 a){
a.salary-= salary;
return *this;
}
private:
string name;
int salary;
int minions;
int weapons;
protected:
void who(){
cout<<"The Mafia Leader is: " << name <<endl;
}
std::string why(){
return"Because he killed the president!";
}
void money(){
cout<<name<<" makes "<< this->salary <<" a year! Located at: "<< this <<endl;
}
void minions1(){
cout<<name<<" has "<<this->minions <<" working for him, located at " << this << endl;
}
void weapons1(){
cout<< name<<" has "<< this->weapons << " located at this secret co-ordinate: "<< this << endl;
}
};
class police : protected question3 {
public:
police(){
question3();
}
void info(){
cout<<"Before captureing the Mafia Leader, here is the relevant info: "<<endl;
who();
cout<<why();
money();
minions1();
weapons1();
}
};
int main(){
police ob1; // or can we use police *ob1 = new police; ?
ob1.info();
return 0;
}
Now in int main I only make an object from the inherited class , how can I then define the variables from the parent class and use them in the inherited class?
I don't know exactly what this question aims for, but the inherited class inherits all members of the base class. It can use the members only when they are protected or public. private members exists, just cannot be accessed
#include <iostream>
struct base
{
base( int aa, int bb ) { a = aa ; b = bb ; }
protected: int a, b ;
};
struct derived : base
{
using base::base ; // inherited constructor (C++11)
derived( int aa, int bb, int cc ) : base(aa,bb) // initialize base with aa, bb
{ c = cc ; }
private: int c = 9 ;
};
int main()
{
derived d1( 1, 2 ) ;
derived d2( 3, 4, 5 ) ;
derived* d3 = new derived( 5, 6 ) ;
// etc.
}
You mean accessed directly right?(but maybe using public member funcs that are present in the base class)
sakonpure6 wrote:
how can I then define the variables from the parent class and use them in the inherited class
You can define the variables in parent class under protected access specifier and the child class can inherit from the parent class protected. Hope that helps.