initializing heap-allocated structs

W

Wolfgang Jeltsch

Hello,

I can initialized, e.g, heap-allocated ints by writing something like
new int(5).
Now I'd like to know if it is possible to do the same thing for struct
types. Say, I have a struct declared by the following lines:
struct S {
int i;
const char c;
}
I want to write something like
new S {5, 'd'}.
Is this possible?

Wolfgang
 
?

=?iso-8859-1?Q?Juli=E1n?= Albo

Wolfgang Jeltsch escribió:
types. Say, I have a struct declared by the following lines:
struct S {
int i;
const char c;
}
I want to write something like
new S {5, 'd'}.
Is this possible?

You can add a constructor to S.

S (int i, const char c) : i (i), c (c) { }

And then use
new S (5, 'd');

Regards.
 
S

Samuele Armondi

Wolfgang Jeltsch said:
Hello,

I can initialized, e.g, heap-allocated ints by writing something like
new int(5).
Now I'd like to know if it is possible to do the same thing for struct
types. Say, I have a struct declared by the following lines:
struct S {
int i;
const char c;

Add a constructor:
S(int _i, char _c) : i(_i), c(_c);
}
I want to write something like
new S {5, 'd'}.

Make that new S(5, 'd');

HTH,
S. Armondi
 
S

Samuele Armondi

Samuele Armondi said:
Add a constructor:
S(int _i, char _c) : i(_i), c(_c);

Sorry, typo slipped in... That should be:
S(int _i, char _c) : i(_i), c(_c) {};
 
M

Mike Wahler

Wolfgang Jeltsch said:
Hello,

I can initialized, e.g, heap-allocated ints by writing something like
new int(5).
Now I'd like to know if it is possible to do the same thing for struct
types. Say, I have a struct declared by the following lines:
struct S {
int i;
const char c;
}
I want to write something like
new S {5, 'd'}.
Is this possible?

Yes, and the mechanism (knows as a 'constructor') does
not depend upon where the memory is allocated:

#include <iostream>

struct S
{
int i;
const char c;
S(int ii, char cc) : i(ii), c(cc) { } /* constructor */
};

int main()
{
/* automatic storage: */
S obj(5, 'd');
std::cout << obj.i << '\n'; /* prints 5 */
std::cout << obj.c << '\n'; /* prints d */

/* allocated storage: */
S *ptr = new S(5, 'd');
std::cout << ptr->i << '\n'; /* prints 5 */
std::cout << ptr->c << '\n'; /* prints d */

delete ptr;
return 0;
}

Read about constructors in any quality C++ textbook.

-Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top