OverDoze
OverDoze

Reputation: 13

Function that returns just the constructor

#include <iostream>


struct something{
    int i;

    something(int i) : i(i) {}
};

class otherthing {

    otherthing(){}

    static something foo(int value)
    {
        return { value };
    }
};

In this example what the foo function returns? Am I understand correctly that it creates an object on the heap and returns a pointer? Is this considered bad style? Or is it ok for structs and not classes?

I can feel that it might be a stupid question but I tried to google it and I could not find the answer. I apologize in advance if this is dumb.

Upvotes: 0

Views: 66

Answers (3)

Yksisarvinen
Yksisarvinen

Reputation: 22176

In this example what the foo function returns?

Object of type something, initialized with value value.

Am I understand correctly that it creates an object on the heap and returns a pointer?

No. It creates an object with automatic lifetime (typically associated with stack memory). It returns that object and no pointer.

Is this considered bad style?

It's quite useless in this example, but in general this approach is called factory pattern. It allows you to separate creation of object from other logic, and that would be good style actually.

Or is it ok for structs and not classes?

The only difference between struct and class in C++ is the default access modifier. In struct member are by default public, in class members are by default private.

Upvotes: 4

Jasper Kent
Jasper Kent

Reputation: 3676

In C++ (unlike C#) classes and structs are identical but for one tiny detail: the default access level for a class is private; for a struct it's public.

In your example, a something object is created on the stack in foo. When foo is called, e.g.

something s = otherthing.foo();

then the object is copied into s on the stack.

No pointers are involved.

Upvotes: 0

t.niese
t.niese

Reputation: 40842

Am I understand correctly that it creates an object on the heap and returns a pointer?

No, it does not return a pointer, it returns an instance of something with automatic storage duration (which is commonly allocated on the stack) which for the return will utilize copy elision

Or is it ok for structs and not classes?

A struct and a class only differ in the default access modifier, besides that there is no difference.

Upvotes: 1

Related Questions