Click here to Skip to main content
15,884,099 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Their is a Spreadsheet /*then a*/ CreateObject(){} //I am confused how this is legal.
What does it mean?

C++
Spreadsheet CreateObject() { return Spreadsheet(3, 2); };
int main(){ }


What I have tried:

Their is a Spreadsheet /*then a*/ CreateObject(){} //I am confused how this is legal.
What does it mean?


Spreadsheet CreateObject() { return Spreadsheet(3, 2); };
int main(){ }
Posted
Updated 13-Dec-18 21:06pm
v2
Comments
Mohibur Rashid 13-Dec-18 22:48pm    
What exactly are you talking about?

This a function implementation in the format Object function body like
C++
int func() { return 0; }; 
It is not a good idea for objects because the Spreadsheet object is allocated in the function body and the a copy on the stack.

Better is to work with object pointers:
C++
Spreadsheet* CreateObject() { return new Spreadsheet(3, 2); };
Which you wont write into a function. And you need to delete the Spreadsheet* somewhere.
 
Share this answer
 
That is perfectly legal (and idiomatic) C++ code, due to RVO[^] there is usually no performance loss.
 
Share this answer
 
Comments
KarstenK 14-Dec-18 5:17am    
Thanks for the info. But it has its traps: https://docs.microsoft.com/en-us/previous-versions/ms364057(v=vs.80)
CPallini 14-Dec-18 5:59am    
You are welcome. Traps? You know, C++ has tons of them. As a matter of fact programming in C++ is like playing Minesweeper. :-D
By the way 'naked new' usage is also discouraged nowdays, in favour of smart pointers, see for instance:
https://docs.microsoft.com/en-us/cpp/cpp/smart-pointers-modern-cpp?view=vs-2017
It is worth nothing the article is, in turn, a bit dated:
auto song2 = make_unique<song>(L"Nothing on You", L"Bruno Mars");
would be suggested, today :-)
KarstenK 14-Dec-18 6:55am    
Smart pointers is a good point.

My C++ skills are a bit "old school" now ... ;-)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900