Composition

Hi, may I know if there is a way to B object without calling A object beforehand?

class A{
private:
int attackPower;
public:
void setPower(){
cout<<attackPower;
}
A(int a)
{
attackPower=a;
}
};
class B{
private:
A eob;
public:
B(A ee)
:eob(ee)
{
}
void show()
{
eob.setPower();
}
};

int main()
{
//A obj(1); What if I never declare this first?
B no(obj); //Is there a way to call B object(which has A object as
//private variable)
no.show();
}
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

#include <cstdio>
#include <string>
using namespace std;

// Base class
class Animal {
	string _name;
	string _type;
	string _sound;
	// private constructor prevents construction of base class
	Animal() {};
protected:
	// protected constructor for use by derived classes
	Animal(const string & n, const string & t, const string & s)
		: _name(n), _type(t), _sound(s) {}
public:
	void speak() const;
	const string & name() const { return _name; }
	const string & type() const { return _type; }
	const string & sound() const { return _sound; }
};

void Animal::speak() const {
	printf("%s the %s says %s\n", _name.c_str(), _type.c_str(), _sound.c_str());
}

// Dog class - derived from Animal
class Dog : public Animal {
public:
	Dog(string n) : Animal(n, "dog", "woof"){};
};

// Cat class - derived from Animal
class Cat : public Animal {
public:
	Cat(string n) : Animal(n, "cat", "meow"){};
};

// Pig class - derived from Animal
class Pig : public Animal {
public:
	Pig(string n) : Animal(n, "pig", "oink"){};
};

int main(int argc, char ** argv) {
	Dog d("Rover");
	Cat c("Fluffy");
	Pig p("Arnold");

	d.speak();
	c.speak();
	p.speak();


}
Last edited on
Duplicate of:

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

Please DON'T start multiple threads for the same question.
Topic archived. No new replies allowed.