-2

Can a member function in class have a return type of another class?

class A
{
    int a,b;
public:
    B func(int x); // func returns type B which is another class
};

class B
{
};

Is this allowed?

Slava
  • 43,454
  • 1
  • 47
  • 90
d.a
  • 7
  • 1
  • 3

3 Answers3

1

Yes, you can return any valid type and if that type allows that, there are no additional restrictions on what a member function can return vs regular function.

Though in your code example func() cannot return object of type B as it is not defined there yet. You would need to move class B definition before class A or use forward declaration and then only declare (not define) A::func there, and then you can define (implement) it only after class B definition:

class B;

class A {
public:
    B func( int x ); // declared
    B func2() { return B{}; } // this would not compile with forward declaration of B
};

class B {
};

// this definition must see class B defined, not forward declared
B A::func( int x ) 
{
    return B{};
}

Additional details about forward declaration can be found here

Community
  • 1
  • 1
Slava
  • 43,454
  • 1
  • 47
  • 90
0

Yes, as long as the compiler knows about B before your declaration for func. Either move the definition for class B {}; above class A, or forward declare B by writing class B; before class A.

0x5453
  • 12,753
  • 1
  • 32
  • 61
0

Yes, this is allowed as long as you put the classes in order. Currently, your example does not work. It is:

class A
{
    int a,b;
public:
    B func(int x); // func returns type B which is another class
};

class B
{
};

You either need to put class B before A, like this:

class B
{
};
class A
{
    int a,b;
public:
    B func(int x); // func returns type B which is another class
};

Or Forward declare it:

class B; //Forward Declaration.
class A
{
    int a,b;
public:
    B func(int x); // func returns type B which is another class
};

class B
{
};

Otherwise, your code should work.

Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88