c++ - Return value from Derived class to Base class -


i have value in derived class want return using function base class, possible? or have have variable declared in base class so?

would call function in derived class?

class base {     public:         int getnum() const { return number; } };  class derived : public base {     private:         int n = 50; }; 

i have value in derived class want return using function base class, possible?

yes, can use reference passed base classes constructor so:

class base {     public:         base(int& number_) : number(number_) {}          int getnum() const { return number; }     private:         int& number; };  class derived : public base {     public:         derived() : base(n) {}     private:         int n = 50; }; 

another way (without using virtual getnum() const;) using templated base class (aka static polymorphism):

template <typename d> class base {     public:         int getnum() const { return static_cast<d*>(this)->getnum(); } };  class derived : public base<derived> {     public:         derived() {}         int getnum() const { return n; }     private:         int n = 50; }; 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -