angry_pacifist
angry_pacifist

Reputation: 45

C++ access to private members

Hi I am reading chapter 4 in Joshi's C++ Design Patterns and Derivatives Pricing and I do not understand some parts of the code. We have a class PayOff and we want to define a class VanillaOption that has PayOff as a member. In order to do this effectively he uses a virtual copy constructor.

#ifndef PAYOFF_H
#define PAYOFF_H

class PayOff
{
private:
public:
    PayOff(){}
    virtual double operator() (double Spot) const = 0;
    virtual PayOff* clone() = 0;
    virtual ~PayOff(){}
};

class PayOffCall : public PayOff
{
private:
    double Strike;
public:
    PayOffCall(double Strike_);
    virtual PayOff* clone(){return new PayOffCall(*this);}
    virtual ~PayOffCall(){}
};
#endif 



#ifndef VO_H
#define VO_H
#include "PayOff.h"

class VanillaOption
{
private:
PayOff* ThePayOffPtr;               
double Expiry;
public:
VanillaOption(PayOff&,double );     //constructor
VanillaOption(VanillaOption& original) {thePayOffPtr = original.thePayOffPtr->clone(); Expiry = original.Expiry;}       //copy constructor
VanillaOption& operator=(VanillaOption&);       

~VanillaOption();
 };





#endif

I don't understand how the copy constructor of VanillaOption can access the private members of original i.e. why I can do thePayOffPtr = original.thePayOffPtr->clone(); and Expiry = original.Expiry;. Can anybody help with this? Many thanks in advance.

Upvotes: 1

Views: 261

Answers (3)

Sean
Sean

Reputation: 62472

The way to think of it is that a class can access it's own private parts. If it couldn't then you'd have to write methods to expose the implementation in order to facilitate things like copy construction, and this would compromise encapsulation.

Upvotes: 1

tez
tez

Reputation: 5300

While coding for a class,if you need to access the members(instant variable or methods) of some other class,it is necessary that they are public.Public members of a class can be accessed from any class by creating an object to that class.getter and setter methods are good examples for understanding this.Usually instant variables are declared private while methods are declared public.So we can only use these methods to reach instant variables but not directly.

Upvotes: 0

cdhowie
cdhowie

Reputation: 169008

Access controls apply to the class as a whole, not to instances. Methods of a class have access to private members defined in that class, even on other objects of the class. Even though the constructor runs on a different object (this != &original), you are still able to access the private members of original because the constructor is part of the class where the private members are defined.

Remember: methods and constructors belong to the class itself, not to instances!

Upvotes: 8

Related Questions