Reputation: 18068
Is it possible to initialize in dynamic way using pointers but just after the struct definition?
Please at the example. I tried that but I get an exception when I try cout << a->val << endl;
#include "stdafx.h"
#include <iostream>
using namespace std;
struct A{
public:
int val = 0;
A(){}
}*a,b,c;
int _tmain(int argc, _TCHAR* argv[]){
cout << a->val << endl;//EXCEPTION
cout << b.val << endl;
int x;
cin >> x;
return 0;
}
Upvotes: 0
Views: 486
Reputation: 24269
Your code
struct A{
public:
int val = 0;
A(){}
}*a,b,c;
defines the structure A
and declares three global variables, a
, b
, c
.
a
is of type 'A*' - i.e. pointer to type A
, b
and c
are instances of type A
.
Global variables of simple, base types (e.g. ints, pointers, etc), default to 0.
The result is equivalent to this:
struct A{
public:
int val = 0;
A(){}
};
A* a = NULL;
A b;
A c;
When your code then tries to use a
without assigning a value to it, it is dereferencing a NULL pointer and crashes.
Upvotes: 1
Reputation: 56549
Yes
struct A
{
// ...
} *a { new A };
and somewhere suitable:
delete a;
Generally bare pointers are not recommended, you should avoid them and if you really need pointers try to use smart pointers such as std::unique_ptr
and std::shared_ptr
Upvotes: 2