Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Proper Way To Have Class Object Instance Variable

$
0
0
I am not entirely sure how to put what I am trying to do in words, but I can put it in code. I have managed to isolate the problem down to a very simple case, but cannot seemingly make any headway no matter what I google for. I want to have an object of one class (Bar) be an instance variable of another class (Foo). The issue I am running into is that when I make a Bar instance variable, unless Bar has an empty constructor g++ freaks out with the error message " error: no matching function for call to `Bar::Bar()'" My Code, as I would like it to work, is below.

// code doesn't work.
#include <iostream>

using namespace std;

class Bar {
	private:
		int a;
	public:
		Bar (int _a) {
			a = _a;
		}

		void print() {
			cout << a << "\n";
		}
};

class Foo {
	private:
		Bar b;
	
	public:
		Foo() {
			b(5);
		}

		void print() {
			b.print();
		}
};

int main () {
	Foo f;
	f.print();
}



If I write it with an empty constructor for Bar, and the Foo constructor uses a temporary variable, then I can get it to work, but this seems needlessly messy, and I feel like I am just working around a problem that should be solved another way (see below).

// code does work, but seems needlessly complicated
#include <iostream>

using namespace std;

class Bar {
	private:
		int a;
	public:
		Bar () {
			a = 42;
		}

		Bar (int _a) {
			a = _a;
		}

		void print() {
			cout << a << "\n";
		}
};

class Foo {
	private:
		Bar b;
	
	public:
		Foo() {
			Bar tmp(5);
			b = tmp;
		}

		void print() {
			b.print();
		}
};

int main () {
	Foo f;
	f.print();
}



What is the proper way to do this without using an empty constructor and temporary variable? What is the correct way to say what I am trying to do? Thanks for any help.

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>