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?
class A {
friendclass 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.
#include <iostream>
usingnamespace std;
class A {
friendclass 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.