Home > other >  friend function pointer parameter in constructor
friend function pointer parameter in constructor

Time:01-30

i'm trying to create a costructor in the form

class A {
public:
    A(void (*initializer)(A&))
    {
        initializer(*this);
    }
};

where initializer take a reference to the instance he's passed and can make custom operation on variable it is initializing. Is there a way to make such a function friend so it can access to private variables too?

CodePudding user response:

Here is a simple way:

class Impl
{
public:
    int x;
    int y;
};

class A
{
public:
    A(void (*initializer)(Impl&))
    {
        initializer(_impl);
    }

private:
    Impl _impl;
};

This hides _impl from everyone except initializer. And since nobody other than initializer can access _impl at all, the members of of class Impl can be public, making it easy for initializer to mutate them.

CodePudding user response:

Other than listing all the functions you want to pass pointers to as friends separately, no. An alternative may be to separate the data into a base class with public members you inherit privately from:

struct AData
{
    int m_privateInt;
    ...
};

class A : private AData {
public:
    A(void (*initializer)(AData&))
    {
        initializer(*this);
    }
};

You may need to also pass a reference to A, if you want to access its member functions in initializer.

  •  Tags:  
  • Related