Class Derivation

Why is it that within class B, even though it inherits class A, I can't call the print2 method? However, I can call the print2 method from an object of B...just not from within B itself. Why is this?

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
  class A {
	friend class B;
public:
	A() {
		cout << "Constructor A" << endl;
	}
	void print2()
	{
		cout << "Hello" << endl;
	}
	
};
class B : public A {
	
public:
	int i = 0;
	string hello;

	B(class A myClass, int j)
	{
		myClass.print2();
	}
	void workMe()
	{
		cout << "Work being done" << endl;
	}
	print2(); //function definition not found error
};
int main()
{
	A jan;
	B newB(jan, 2);
	newB.print2(); //this produces no error
	system("pause");
    return 0;
}
What are you trying to do in line27? It should be part of a function definition. If you are trying to define it you don't need to as it has been defined in the parent function A. If you just want it to run every time one is created the function needs to be in the constructor.
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
 #include <iostream>
 
 using namespace std;
 
  class A {
	friend class B;
public:
	A() {
		cout << "Constructor A" << endl;
	}
	void print2()
	{
		cout << "Hello" << endl;
	}
	
};
class B : public A {
	
public:
	int i = 0;
	string hello;

	B(class A myClass, int j)
	{
		myClass.print2();
	}
	void workMe()
	{
		cout << "Work being done" << endl;
	}
//	print2(); //don't need here because it is in class A
};
int main()
{
	A jan;
	B newB(jan, 2);
	newB.print2(); //this produces no error
	system("pause");
    return 0;
}
I'm not exactly sure why I tried to place it there. I should have placed it in the constructor. It works in the constructor. Thanks for helping me sort out the confusion.
Topic archived. No new replies allowed.