Classes - initializers

closed account (jvqpDjzh)
Why this gives me an error?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Foo
{
	const int x;
public:
	Foo( int limit ) : 
		x( limit )
	{		
	}
};

class Bar
{
	Foo f1(300);//error: 300
};


//Is maybe because I can't initialize a member class outside the constructor?
Last edited on
|@line 13, you are trying to initialise f1 with a value of 300. you can only do that in executable code, like in a function or something.

1
2
3
4
5
6
7
8
9
class Bar
{
	Foo f1;

        Bar()
       {
           f1 = Foo(300);//error: 300
        }
};


or use a pointer:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Bar
{
	Foo* f1;

        Bar()
       {
           f1 = new Foo(300);//error: 300
        }

        ~Bar()
        {
            delete f1;
        }
};
closed account (jvqpDjzh)
Yes, basically we can't initialize an object outside a constructor, that's what I thought.
You can use the initializer list within Bar
1
2
3
4
5
6
7
8
9
10
11
12
13
class Foo
{
  int value;

  Foo( const int x ) :value( x ) {}
};

class Bar
{
  Foo my_foo;

  Bar( void ) :my_foo( 300 ) {}
};
closed account (jvqpDjzh)
Yes, that's what I did ;)
Topic archived. No new replies allowed.