I have a class with two constructors, one that takes no arguments and one that takes one argument.
Creating objects using the constructor that takes one argument works as expected. However, if I create objects using the constructor that takes no arguments, I get an error.
For instance, if I compile this code (using g++ 4.0.1)...
class Foo { public: Foo() {}; Foo(int a) {}; void bar() {}; }; int main() { // this works... Foo foo1(1); foo1.bar(); // this does not... Foo foo2(); foo2.bar(); return 0; }
... I get the following error:
nonclass.cpp: In function ‘int main(int, const char**)’: nonclass.cpp:17: error: request for member ‘bar’ in ‘foo2’, which is of non-class type ‘Foo ()()’
Why is this, and how do I make it work?
Friend functions are actually not class member function. Friend functions are made to give private access to non-class functions. You can declare a global function as friend, or a member function of other class as friend.
1 Answer. Friend function is not a member of the class.
The "private within this context" error refers to the fact that the functions addShipment , reduceInventory and getPrice are not members or friends of the class Product , so they cannot use its private members.
Just for the record..
It is actually not a solution to your code, but I had the same error message when incorrectly accessing the method of a class instance pointed to by myPointerToClass
, e.g.
MyClass* myPointerToClass = new MyClass(); myPointerToClass.aMethodOfThatClass();
where
myPointerToClass->aMethodOfThatClass();
would obviously be correct.
Foo foo2();
change to
Foo foo2;
You get the error because compiler thinks of
Foo foo2()
as of function declaration with name 'foo2' and the return type 'Foo'.
But in that case If we change to Foo foo2
, the compiler might show the error " call of overloaded ‘Foo()’ is ambiguous"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With