Class fields

Hi,

I'm trying to create a class with an object field. I want to create the object on the stack rather than the heap, but when I define it, it seems to call the default constructor because when I try to set it inside the class constructor to an object instantiated with another overload of the field's constructor it tries to call the copy constructor on the field.

The type of the field doesn't have a copy constructor, so what I'm asking is whether there's a way to define the property in the class and call the correct constructor overload (with parameters) without having to instantiate the object with the default parameter and then use the copy constructor to assign it?

If possible I'd like to avoid having to new the object and store a reference.

1
2
3
4
5
6
7
8
9
10
11
  class Example
  {
    private:
      Test testObject;
    public:
      Example()
      {
        testObject = Test(52);
        // This tries to call the copy constructor.
      }
  }
ok this seems to be working. I'm not sure if I understand the question.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Test {
public:

	int val;
	Test(int i):val(i){
	}

};

class Example
{
public:
	Test testObject;

	Example():testObject(Test(52)) {
	}
};

Last edited on
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
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
using namespace std;

class Test {
  private:
    int testInt;
      
public:
	Test() {
	}
	
	friend class Example;
};

class Example{
    private:
      Test exampleTest;
      
      public:
      Example(int i) {
          exampleTest.testInt = i;
      }
      
      int getTestInt() {
       return exampleTest.testInt;   
      }
};


int main()
{
  
  Example myExample(52);
  
  cout << myExample.getTestInt();
  
  return 0;
}
Registered users can post here. Sign in or register to post.