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)

9
  • Why do you need the Base* anyway? Commented Nov 21, 2022 at 1: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. Commented Nov 21, 2022 at 1:50
  • @NathanPierson This is just an example. But in the real case I think I would use it mostly to pass to a functions. Commented Nov 21, 2022 at 1:51
  • If you want to pass the address of a variable to a function, that variable must be declared before-hand. Commented Nov 21, 2022 at 1: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. Commented Nov 21, 2022 at 1:53

1 Answer 1

1
class Base {};

Base base, *ptr = &base;

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, got it! Then I'll be using 2 lines.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.