user49535
user49535

Reputation: 15

Making constructor of a second class a friend function in the first class

I have two classes with name firstClass and secondClass. I managed to make the secondClass friend to firstClass. I am now trying to make only the secondClass constructor as a friend and not the entire class. First I get the error: ‘secondClass’ does not name a type and trying to fix it with forward declaration gives error: invalid use of incomplete type ‘class secondClass'. Is it possible to make secondClass contructor as a friend to first class.

#include <iostream>

using namespace std;

/*
//these forward declaration, do not solve the problem
class firstClass;
class secondClass; 
secondClass::secondClass(const firstClass& fc);
*/

class firstClass
{
private:
    int value;

    friend secondClass::secondClass(const firstClass& fc);
    //friend class secondClass; //this works
public:
    firstClass(int val = 0): value(val){}

};

class secondClass
{

public:
    secondClass(int val = 0): value(val){}
    secondClass(const firstClass& fc)
    {
        value = fc.value;
    }

    int getValue()
    {
        return value;
    }

    int value;
};


int main()
{
    firstClass fc(5);

    secondClass sc(fc);

    cout<<sc.value;

}

Upvotes: 0

Views: 333

Answers (1)

scohe001
scohe001

Reputation: 15446

Here's the proper way to do the forward declarations:

//secondClass needs to know the type firstClass exists to take it as an argument to the ctor
class firstClass;

class secondClass
{   
  public:
    secondClass(int val = 0): value(val){}
    secondClass(const firstClass& fc); //Just declare that this function exists

    int getValue()
    {
        return value;
    }

    int value;
};

class firstClass
{
private:
    int value;

    //Since this function is declared, this works
    friend secondClass::secondClass(const firstClass& fc);
public:
    firstClass(int val = 0): value(val){}

};

//Finally, now that firstClass is implemented, we can implement this function
secondClass::secondClass(const firstClass& fc)
{
    value = fc.value;
}

See it run here: https://ideone.com/ZvXIpw

Upvotes: 1

Related Questions