0

I have a c++ problem where I need to move my derived class's functions to the base class to "clean up" my code. This is the code that I want to move:

double Resistor::getVolt() { if (connection_a->getCharge() > connection_b->getCharge()) return connection_a->getCharge() - connection_b->getCharge(); else return connection_b->getCharge() - connection_a->getCharge(); } double Resistor::getCurr() { if (connection_a->getCharge() > connection_b->getCharge()) return (connection_a->getCharge() - connection_b->getCharge())/resistance; else return (connection_b->getCharge() - connection_a->getCharge())/resistance; } 

I need to move all this and still reach the variables connection_a & connection_b without making the private.

1
  • 3
    Good. What are you waiting for? Commented Jun 25, 2013 at 16:45

1 Answer 1

2
class Component{ protected: Component *connection_a, *connection_b; virtual double getCharge(); public: virtual ~Component(); }; class Resistor : public Component{ public: virtual double getVolt(); virtual double getCurr(); virtual ~Resistor(); }; 

From getVolt() you are free to read all non-private fields of the parent. From the baseclass you are not allowed access to any of the derived class's variables directly. You could however call virtual methods offered by the baseclass that are overwritten in the derrived class knowing that the ones that will be called depends on the instance's class type.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.