returning class instance from a function

Is there any way to return a class instance from a function?

1
2
  class CLASS{...}
  CLASS func(){return CLASS(...);}
Yes.
How?!
The code you have posted looks OK. You just need to remove or replace the dots.
1
2
class CLASS{};
CLASS func(){return CLASS();}
i didnt use dots the dots mean i didnt post the code in there.
And when i try to compile it it sais "Error:CLASS does not name a type".
It's hard to know what the problem is without seeing the code.
You return a class instance the same way you return any other type of variable.
1
2
3
4
5
6
CLASS funct()
{
   CLASS myClass; // Create an instance of the class.

   return myClass;  // Return that instance of the class.
}
Sorry my bad :/
I need to return an instance of another class.
What? funct() is not a member of any class so what exactly is the problem?

Umm sorry yea i kinda messed it up.
What i mean is I wanna make a class with a fucntion that can return an instance of another class.
The function must be in the first class.
Please show the smallest possible complete program that illustrates your question.

Idk something like:
1
2
3
4
5
6
7
8
9
10
11
12
class CLASS_A
{
//declare stuff here;
}

class CLASS_B
{
CLASS_A func();//RETURNS AN INSTANCE OF CLASS_A
}

CLASS _B cls_b;
CLASS_A cls_a = cls_b.func();
Last edited on
Then the snippet I posted should work for this case as well, as long as your properly scope the function.

1
2
3
4
5
6
CLASS_A CLASS_B::funct()
{
   CLASS_A myClass; // Create an instance of the class.

   return myClass;  // Return that instance of the class.
}
It gives me the error:CLASS_A does not name a type.
Where did you declare/implement this function? Again show the code that generates this message.

Actually now that i think about it,
is there any way to create an instance of another instance?
Like:
1
2
3
4
5
6
class A
{
blah bla blah
}
A a1(blah blah);
A a2(a1);


I am basically trying to make a move an instance from an array to another.
Or is there any way i can do something like:

1
2
3
4
5
class A
{
  A();
  A(A a);//creates an instance from another instance
}
Topic archived. No new replies allowed.