0

There is a one line syntax to create an instance and pointer to it, in the heap allocation. Is there one line syntax for the same purpose but with stack allocation?

#include <iostream>

class Base {};

int main()
{
    //Base* ptr = new Base(); // heap

    Base base;
    Base* ptr = &base; // stack  

    return 0;
}

I have no problem to use 2 lines, just thought maybe there is a special syntax for this case (I'm moving from Python :D)

Nick
  • 11
  • 1
  • Why do you need the `Base*` anyway? – Nathan Pierson Nov 21 '22 at 01:39
  • It is possible to define more than one variable in a single declaration statement e.g. `Base base, *ptr = &base;`. It's not possible to eliminate the two parts entirely, since both variables (`base` and `ptr`) have names. BTW - terms like "heap" and "stack" are not actually part of C++ (in this context) - heap and stack are specific concepts from some implementations (particular compilers and host systems) but not relevant to all implementations. – Peter Nov 21 '22 at 01:50
  • @NathanPierson This is just an example. But in the real case I think I would use it mostly to pass to a functions. – Nick Nov 21 '22 at 01:51
  • If you want to pass the address of a variable to a function, that variable must be declared before-hand. – Peter Nov 21 '22 at 01:52
  • You can just base `&base` to a function. You can write your function to take a reference and just pass `base` itself. That's why I asked about the actual use case, because it's not clear when you'd want this. – Nathan Pierson Nov 21 '22 at 01:53
  • @Peter Thanks for detail explanation. So does it mean that the syntax from my example can't guarantee that it would be heap or stack and it will depend on compiler? – Nick Nov 21 '22 at 01:57
  • @Nick - I'm saying that heap and stack are meaningless in the context of C++, because they are implementation details that are not required by the C++ standard (and don't always occur in all implementations). In C++, the terminology is concerned with life cycle of objects (e.g. a variable with automatic storage duration [lifetime bound to its containing scope or context], a dynamically allocated object [such as is managed using `new` and `delete`], and statically allocated objects). – Peter Nov 21 '22 at 02:17
  • @NathanPierson Got it, thanks. I have no real task yet, just learning syntax, and, to be honest, it's not too clear for me at the moment when it is better to use pointers or references. I just notice that pointer looks like has more functionality (iteration by +-1, ability to reassign address, delete variable from heap (if i'm not wrong) ) but in case of references looks like it can simplify a code. – Nick Nov 21 '22 at 02:18
  • @Peter Got it. Then I meant dynamic and automatic storage :) – Nick Nov 21 '22 at 02:26

1 Answers1

1
class Base {};

Base base, *ptr = &base;

But I wouldn't consider it "a well formatted code".