Jump to content
  • Advertisement
Sign in to follow this  
tom_mai78101

How to: Class function returning a primitive type pointer.

This topic is 2351 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Example:

class MyClass
{
public:
int* function(int test);
}

int* MyClass::function(int test) //<------- ERROR!!
{
int* ptr = &test; //Anything goes in this function, doesn't matter.
return ptr;
}


I get an error saying:

error C2511: 'int *MyClass::function(int)' : overloaded member function not found in 'MyClass'[/quote]

Do you know how to return a pointer of primitive type from a class function? Ignore the function code in the example, if you will. Thanks in advance.

Share this post


Link to post
Share on other sites
Advertisement
1: Place a semicolon after the class block.

2: Avoid using the word "function" as a symbol. While it is not a C++ keyword, it is a keyword in many other languages. To prevent future confusion, name the function to match its logical meaning.

Share this post


Link to post
Share on other sites
Also, returning a pointer to test is very dangerous, because test was initialized for the function block only, and was copied by value, ss soon as the program exits the function, test doesn't exist anymore, and ptr points to an invalid area.

This however would work, and does what you want it to do:
class MyClass
{
public:
int* func(int& test);
};

int* MyClass::func(int& test)
{
int* ptr = &test;
return ptr;
}

Share this post


Link to post
Share on other sites

This however would work, and does what you want it to do:
class MyClass
{
public:
int* func(int& test);
};

int* MyClass::func(int& test)
{
int* ptr = &test;
return ptr;
}



Thanks. I'm just looking for this.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!