My program has the following objectives:
- To overload the base class extraction operator in the derived class: I tried doing this using
static_cast<Derived> (derived)but ended up in run time error. I know that friend won't get inherited. I had redeclared friend function in my derived class as well with different arguments to handle the derived class data members. - To handle static data members: I have to change the values of the static data members. I have to use them in combination with non static data members as well. I tried using static getters and setters. But couldn't succeed.
Here is my code below:
#include <iostream>
using namespace std;
class Base {
private:
string name;
int rollNum;
public:
friend std::istream& operator>>(std::istream& in, Base &base);
};
std::istream& operator>>(std::istream& in, Base &base) {
string name;
int rollNum;
cout << "Enter name: ";
in >> base.name;
cout << "Enter roll no: ";
in >> base.rollNum;
return in;
}
class Derived : public Base {
private:
int myNumOne;
static int x;
static int y;
public:
friend std::istream& operator>>(std::istream& in, Derived Derived);
void add();
static void init();
static int getX();
static int getY();
};
std::istream& operator>>(std::istream & in, Derived derived) {
in >> static_cast<Derived> (derived);
cout << "Enter a number: ";
in >> derived.myNumOne;
return in;
}
static void Derived::init() {
x = 100;
y = 100;
}
static int Derived::getX() {
return x;
}
static int Derived::getY() {
return y;
}
void Derived::add() {
myNumOne += getX() + getY();
cout << "Number = " << myNumOne << endl;
}
int main() {
Derived obj;
cin>>obj;
Derived objOne;
objOne.add();
Derived objTwo;
objTwo.add();
return 0;
}
I am getting the error as follows:
newmain.cpp:43:31: error: cannot declare member function 'static void Derived::init()' to have static linkage [-fpermissive]
static void Derived::init() {
^
newmain.cpp:48:30: error: cannot declare member function 'static int Derived::getX()' to have static linkage [-fpermissive]
static int Derived::getX() {
^
newmain.cpp:52:30: error: cannot declare member function 'static int Derived::getY()' to have static linkage [-fpermissive]
static int Derived::getY() {
^
staticin front of the function definitions. - πάντα ῥεῖundefined reference to Derived::xin getX(), getY() and init() methods. - Praveen VinnyDerived::xandDerived::yas well. - πάντα ῥεῖ