Simon Righley
Simon Righley

Reputation: 4969

c++ calling method from outside of a class

Ok, I reduced my problem to something that looks really silly but I simply cannot understand why this:

#include <iostream>
class ABC{
public:
    void Print() { std::cout<<"ABC_TEST!\n"; }
};

int main(){
    Print();
    return 0;
}

Gives me: error: identifier "Print" is undefined Thanks in advance!

Upvotes: 1

Views: 6783

Answers (3)

Aniket Inge
Aniket Inge

Reputation: 25695

It should be like this :

#include <iostream>
class ABC{
public:
    void Print() { std::cout<<"ABC_TEST!\n"; }
};

int main(){
    ABC abc;
    abc.Print();
    return 0;
}

You need to create an object of type ABC before you can call instance methods(or member functions which are not static)

Alternatively, Print() can be a static function and you will be able to call it with the :: operator.

class ABC {
   public:
     static void Print() { std::cout << "ABC_TEST\n"; }
};

int main()
{
   ABC::Print();
   return 0;
}

Above all else, Print() can also be a global function:

void Print()
{
   std::cout << "ABC_TEST\n" ;
}

int main()
{
   Print();
   return 0;
}

Upvotes: 3

Andy Prowl
Andy Prowl

Reputation: 126412

Print() is a member function of your ABC class, you need an object to invoke it on:

int main()
{
    ABC abc; // This creates an instance of ABC

    abc.Print();
//  ^^^^
//  This invokes member function `Print()` on the object abc.

    return 0;
}

The address of abc will be passed as an implicit first parameter to function Print(): that parameter will be accessible inside of Print() (more generally, inside an invoked member function) as the this pointer.

If you try calling Print() as if it were a non-member, free function, no implicit this pointer would be passed, and it makes sense that the compiler complains about it.

If you want to be able to invoke Print() the way you did, you should make it a non-member function:

void Print() { std::cout<<"ABC_TEST!\n"; }

int main()
{
    Print(); // This is fine now!
}

Upvotes: 1

juanchopanza
juanchopanza

Reputation: 227370

Print() is a member function of ABC, so you can only call it on an instance of ABC:

ABC abc;
abc.Print();

As a completely unrelated note, in C++ a return with value 0 is implied, so it is not necessary to write return 0.

Upvotes: 1

Related Questions