user2991252
user2991252

Reputation: 788

Returning a pointer from member function c++

If I want to return a pointer from a member-function I first thought the syntax should look like the following:

 char SecondClass:: *getName() {
   return this->name;
 } 

But I got an error-message in Eclipse that it couldn't solve the field "name". Somehow it becomes hidden in this case.

The correct solution is this

 char *SecondClass:: getName() {
   return this->name;
 }

That is putting an * before the classname instead of the function-name.

So my question is: why is the first function not working and what is the difference between these implementations of returning pointers from member-functions?

Upvotes: 2

Views: 146

Answers (3)

n. m. could be an AI
n. m. could be an AI

Reputation: 119847

char SecondClass:: *getName() is a very different function from char *SecondClass:: getName().

The first one not a member function of SecondClass or any other class, thus you cannot refer to this inside it. It happens to return a special kind of pointer called pointer-to-member. Its type is spelled char SecondClass:: * and it is a pointer to a member of type char in class SecondClass. You probably don't want to know any of this just yet.

The ssyntax you want is return-type function-name parameter-list. You want to define a function named SecondClass::getName that returns a char * and takes no parameters, thus char *SecondClass::getName().

Upvotes: 1

Jules Gagnon-Marchand
Jules Gagnon-Marchand

Reputation: 3781

In c++, the signature of a member function is [returnType] [ClassName]::functionName{}

the star is part of the return type, which is char*, or pointer to a char. Your first way of declaring a function is just not valid c++.

Upvotes: 0

Geier
Geier

Reputation: 904

This has nothing to do with pointers. The method is called SecondClass::getName() and it returns a char*. So you can write

char* SecondClass::getName()

or

char *SecondClass::getName()

but you can't put the * between the class name and the method name.

Upvotes: 7

Related Questions