can i create a function which returns a class object?

Hello everyone,as you saw in the topic a was wondering if i could create a function which returns a class object.I writed the following code but obviously it returns me erros.Take a look:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include<iostream>
using namespace std;

class foo()
{
	class one
	{
		public:
			int k;
			one(){k=6;}
		private:
	};

	one tsiou;

	return tsiou; 
	
}


int main()
{
	foo();
	return 0;
}


The compiler tells me that foo is a class "'return' : cannot convert from 'class foo::one' to 'int'"
I understant that the object is declared in a topic area so i tried to made it accesable by the return method.If this is totally wrong are there any other sugestions about how to return a class object from a function.Thanks for your time.

I've never seen a class with a return function. You should write a member function of the class foo that returns an object of the class one. And do not declare classes within classes!
Last edited on
You can't return instances of local classes. You need to declare one outside of foo for that to work.

xander333 wrote:
And do not declare classes within classes!

Nested classes are fine if the nested class strictly "belongs" to the containing class.
You can, but not like this.

You need to first define the class one, then have the function foo of return type one, then (optionally) when you call foo ensure its output is put to a instance of one.

At the moment you have a class foo containing a class one, I'm suprised the compilation doesn't stop earlier.

You need a structure kind of like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class one
{
public:
one() {};
/// ... class features
};

one foo()
{
one result;
return result;
}

int main()
{
one mine = foo();
return 0;
}


edit to add: @xander333 - nested classes are indeed awesome, if you know where to use them.
Last edited on
There is an interesting result of defining a local class inside a function. That is, the class cannot be inheritted from1.

Consider:
1
2
3
4
5
6
7
8
struct Base {};

Base * create()
{
    class Final : public Base {};

    return new Final();
}


1 See Modern C++ Design by Andrei Alexandrescu, section 2.3: Local Classes.
Thank you all guys for your help and your time.

Pax nice and easy tip,i never thought i could do something like that!

Moorecm ouaou ,that's an realy andvance style,i will give it a try (i will search for the book also,i hope i can understant it,since i am a beginner yet.)
Topic archived. No new replies allowed.