How to create object on the stack in C++

1 Answer

0 votes
#include <iostream>
#include <string>
 
class Example {
private:
    int m_A;
    std::string m_Str;
public:
     
    Example() : m_A(0), m_Str("***") {}
     
    void Print() const {
        std::cout << m_A << " " << m_Str << "\n";
    }
};
  
 
int main() {
    Example ex = Example(); // without new = create object on the stack 
      
    ex.Print();
    
    // no need to free (delete), the stack will free the object at the end of the scope 
}
   
   
   
   
/*
run:
   
0 ***
   
*/

 



answered Feb 2, 2023 by avibootz

Related questions

1 answer 206 views
1 answer 114 views
114 views asked Feb 2, 2023 by avibootz
2 answers 213 views
213 views asked Nov 25, 2020 by avibootz
1 answer 87 views
1 answer 79 views
1 answer 263 views
...