Constructing Class in Function to be used Elswhere

Hi. I have three classes.

Image
Text
buttonObj

They all have unique constructors and functions. buttonObj has an Image member and a text member. My problem is that I want these Images and Texts to be constructed WITHIN the constructor of buttonObj, but I ALSO want them to be used in buttonObj::update. So I need to somehow construct the Images and Texts within the constructor of buttonObj, but also be able to use them in another function of buttonObj.

That's a little confusing, if you need any clarification I'd be happy to provide!

Any help would be SUPER! Thanks!
I'm probably misunderstanding, because it sounds like you have the solution already; to make an Image object and a Text object both member objects of the buttonObj class.

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
class Image {
  public:
    void foo() {}
};
class Text {
  public:
    void do_text_stuff() {}
};

class buttonObj {

  public:
    buttonObj()
    : image(), text() // initial image and text with default constructors
    {}

    update()
    {
        image.foo();
        text.do_text_stuff();
    }

  private:
    Image image;
    Text text;
};
Last edited on
Here is a simplified version of what I am doing. By simplified, I mean I cut out all non-essential parts. I cut out ALOT, this is the problem in its most basic form. (It doesn't work :D)

1
2
3
4
5
6
7
8
9
10
11
12
13
class buttonObj {
public:
	string baseImagePath; //Parameter for buttonBase
	image buttonBase; // Create a class-wide variable for buttonBase to be used everywhere in class

	buttonObj(string img) : baseImagePath(img) {
		buttonBase = image(baseImagePath); //Construct and assign buttonBase (???)
	}

	bool update(fullInput snapshot) {
		//Use the newly assigned/constructed buttonBase here!
	}
};


Thanks for the help so far! Hope that clarified everything!
Please provide:
a.) the error message(s), verbatim;
b.) the definition of image.

http://www.cplusplus.com/forum/beginner/1/

In general, prefer to avoid the redundant copy assignment by initializing members in the member-initialization list, rather than the constructor body:
6
7
8
9
10
buttonObj(string img) 
  : baseImagePath{img}
  , buttonBase{baseImagePath} {
  // buttonBase = image(baseImagePath);
}
Last edited on
Topic archived. No new replies allowed.