473,795 Members | 3,157 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

initializing heap-allocated structs

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
Jul 19 '05 #1
4 6782
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.
Jul 19 '05 #2
"Wolfgang Jeltsch" <je*****@tu-cottbus.de> wrote in message
news:bh******** ****@ID-77306.news.uni-berlin.de...
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 Is this possible?

Wolfgang

Jul 19 '05 #3

"Samuele Armondi" <sa************ ****@hotmail.co m> wrote in message
news:3f******** @mk-nntp-1.news.uk.world online.com...
"Wolfgang Jeltsch" <je*****@tu-cottbus.de> wrote in message
news:bh******** ****@ID-77306.news.uni-berlin.de...
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);


Sorry, typo slipped in... That should be:
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
Is this possible?

Wolfgang


Jul 19 '05 #4

Wolfgang Jeltsch <je*****@tu-cottbus.de> wrote in message
news:bh******** ****@ID-77306.news.uni-berlin.de...
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

Jul 19 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
7527
by: mordac | last post by:
Hello, I was wondering if I could get some opinions on how best to handle printing in a max heap data structure. Right now my heap struct looks as thus: typedef struct heapStruct { int* heapArray; int heapSize; int arraySize; int maxSize; } heapStruct; arraySize holds the current number of elements in the array.
7
2369
by: GrandpaB | last post by:
While writing this plea for help, I think I solved my dilemma, but I don't know why the statement that solved the problem is necessary. The inspiration for the statement came from an undocumented VB example I found on the web. I would be most appreciative if someone could explain why this statement is necessary and what does it do? MyArt = New Art ' **** ??????? ****
9
8056
by: Dennis Jones | last post by:
Hi, I have some old code that I am refactoring to use smart pointers and have run into a small problem. My original code looks something like this: class WorkerThread { std::map<int, Handler> &HandlerMap; public: WorkerThread( std::map<int, Handler> &AHandlerMap )
10
3449
by: JurgenvonOerthel | last post by:
Consider the classes Base, Derived1 and Derived2. Both Derived1 and Derived2 derive publicly from Base. Given a 'const Base &input' I want to initialize a 'const Derived1 &output'. If the dynamic type of 'input' is Derived1, then 'output' should become a reference to 'input'. Otherwise 'output' should become a reference to the (temporary) result of the member function 'input.to_der1()' which returns a Derived1 object by value.
0
13324
by: JosAH | last post by:
Greetings, I was asked to write a Tip Of the Week; so here goes: a lot of topics are started here in this forum (and a lot of other forums too) mentioning a problem about sorting data. Examples of two main problem scenarios are like this: 1) an array containing a first name and another array containing a last name and possibly a third array containing the age of a person; how to sort the
5
24819
by: kumarmdb2 | last post by:
Hi guys, For last few days we are getting out of private memory error. We have a development environment. We tried to figure out the problem but we believe that it might be related to the OS (I am new to Windows so not sure). We are currently bouncing the instance to overcome this error. This generally happen at the end of business day only (So maybe memory might be getting used up?). We have already increased the statement heap & ...
10
1911
by: Jason Doucette | last post by:
Situation: I have a simple struct that, say, holds a color (R, G, and B). I created my own constructors to ease its creation. As a result, I lose the default constructor. I dislike this, but it's easy to solve: I just make my own default constructor. Problem: My own default constructor is considered to be *initializing the variable* (even though it doesn't), whereas the original one does not. Thus, when I declare and use it before...
13
2343
by: WaterWalk | last post by:
Hello. When I consult the ISO C++ standard, I notice that in paragraph 3.6.2.1, the standard states: "Objects with static storage duration shall be zero-initialized before any other initialization takes place." Does this mean all non-local objects will be zero-initialized before they are initialized by their initializers(if they have)? For example: int g_var = 3; int main() {}
2
2257
by: Martin Payne | last post by:
I am trying to initialise a structure with random values for all its fields. It is a large structure so I do not want to do it for each element in turn (it would take ages). Please note my structure has the qualification: so it is effectively a block of memory of size 512 bytes although it has integer and string fields. What I would like to do is something like this:
4
9595
by: ggoubb | last post by:
The purpose of the Insert function is to add a new integer in the Heap assuming that it is not already full. If Heap capacity has been reached, it attempts to double the current capacity. If capacity cannot be doubled, it throws FullHeap. Here is the Heap.h file const int MAXSIZE = 4; // Default maximum heap size class Heap // Smart Heap ADT as an array { private: int* ptr; ...
0
9672
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9519
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10437
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10214
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10164
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6780
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5437
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3723
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2920
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.