473,326 Members | 2,048 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

Newing objects in constructor

Hi, Whenever i have a class that contains references to other classes
i keep
end up doing the below. However it doesn't seem so safe or elegant.
How do the
pros initialise subobjects, any ideas to improve the below would be
welcome.

/.h file
class A
{
public:
A();
~A();
private:
SomeMethod();

obj1* pobj1;
obj2* pobj2;
obj3* pobj3;
obj4* pobj4;
};

/.cpp file

A::A()
{
pobj1 = new obj1;
pobj2 = new obj2;
pobj3 = new obj3;
pobj4 = new obj4;

}

A::SomeMethod()
{

pobj1->doSomething();
etc
}

A::~A()
{
delete pobj1;
delete pobj2;
delete pobj3;
delete pobj4;
}
Jun 27 '08 #1
8 1664
tech wrote:
Hi, Whenever i have a class that contains references to other classes
i keep
end up doing the below. However it doesn't seem so safe or elegant.
How do the
pros initialise subobjects, any ideas to improve the below would be
welcome.

/.h file
class A
{
public:
A();
~A();
private:
SomeMethod();

obj1* pobj1;
obj2* pobj2;
obj3* pobj3;
obj4* pobj4;
};

/.cpp file

A::A()
{
pobj1 = new obj1;
pobj2 = new obj2;
pobj3 = new obj3;
pobj4 = new obj4;

}

A::SomeMethod()
{

pobj1->doSomething();
etc
}

A::~A()
{
delete pobj1;
delete pobj2;
delete pobj3;
delete pobj4;
}
Compare your code (which, BTW, doesn't adhere to "The Rule of Three",
read up on it) with this:

/.h file
class A
{
public:
A();
~A();
private:
SomeMethod();

obj1 myobj1;
obj2 myobj2;
obj3 myobj3;
obj4 myobj4;
};

/.cpp file

A::A()
: myobj1()
, myobj2()
, myobj3()
, myobj4()
{
}

A::SomeMethod()
{
myobj1.doSomething();
etc
}

A::~A()
{
}

-----------

If your object *owns* its subobjects, it probably is better if the data
members are represented by objects, not pointers.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jun 27 '08 #2
tech wrote:
Hi, Whenever i have a class that contains references to other classes
i keep
end up doing the below. However it doesn't seem so safe or elegant.
How do the
pros initialise subobjects, any ideas to improve the below would be
welcome.

/.h file
class A
{
public:
A();
~A();
private:
SomeMethod();

obj1* pobj1;
obj2* pobj2;
obj3* pobj3;
obj4* pobj4;
};

/.cpp file

A::A()
{
pobj1 = new obj1;
pobj2 = new obj2;
pobj3 = new obj3;
pobj4 = new obj4;
If the last new throws, you leak the memory for the first three objects. If
you _really_ need pointers at all, consider using std::auto_ptr during
initialization:

A::A() {
std::auto_ptr< obj1 dummy1 ( new obj1 );
std::auto_ptr< obj2 dummy2 ( new obj2 );
std::auto_ptr< obj3 dummy3 ( new obj3 );
std::auto_ptr< obj4 dummy4 ( new obj4 );
pobj1 = dummy1;
pobj2 = dummy2;
pobj3 = dummy3;
pobj4 = dummy4;
}
>
}

A::SomeMethod()
{

pobj1->doSomething();
etc
}

A::~A()
{
delete pobj1;
delete pobj2;
delete pobj3;
delete pobj4;
}
If you go with those pointers, you either need to make the assignment
operator and copy constructor private or implement them in some way that
does the RightThing(tm), whatever that would be in your case. The ones
generated by the compiler will _not_ do the right thing.
More importantly: why do you want pointers in the first place? You could
just do

class A {
type1 obj1;
type2 obj2;
...
};

Nothing in your post shows a genuine need for pointer members.
Best

Kai-Uwe Bux
Jun 27 '08 #3
Hi!

Kai-Uwe Bux schrieb:
A::A() {
std::auto_ptr< obj1 dummy1 ( new obj1 );
std::auto_ptr< obj2 dummy2 ( new obj2 );
std::auto_ptr< obj3 dummy3 ( new obj3 );
std::auto_ptr< obj4 dummy4 ( new obj4 );
pobj1 = dummy1;
You need to "release()" the object from the auto_ptr:
pobj1 = dummy1.release();

But it would be easier to just use auto_ptrs as members (if you _really_
need pointers after all):

class A {
//use const until you implement operator =
const std::auto_ptr<obj1pobj1;
A();
};

A::A()
: pobj1(new obj1)
{}

Frank
Jun 27 '08 #4
>
If the last new throws, you leak the memory for the first three objects. If
you _really_ need pointers at all, consider using std::auto_ptr during
initialization:

A::A() {
std::auto_ptr< obj1 dummy1 ( new obj1 );
std::auto_ptr< obj2 dummy2 ( new obj2 );
std::auto_ptr< obj3 dummy3 ( new obj3 );
std::auto_ptr< obj4 dummy4 ( new obj4 );
pobj1 = dummy1;
pobj2 = dummy2;
pobj3 = dummy3;
pobj4 = dummy4;
}

Actually, I could be seeing something correctly, but won't all your
pointers be destroyed as soon as you leave the scope of the
constructor? Don't you either have to explicitly release the auto_ptr
(i.e. dummy1.release()) after the assignment... of if you can,
declare your pointers in your class as auto_ptrs i.e.:

/.h file
class A
{
public:
A();
~A();
private:
SomeMethod();

std::auto_ptr< obj1 myobj1;
std::auto_ptr< obj2 myobj2;
std::auto_ptr< obj3 myobj3;
std::auto_ptr< obj4 myobj4;

};

A::A()
: myobj1(new obj1),
myobj2(new obj2),
myobj3(new obj3),
myobj4(new obj4)
{
}

Of course, they do not have to be auto_ptrs I guess... but using some
type of smart pointer in the declaration may make your life easier
than just using raw pointers.
Jun 27 '08 #5
bjeremy wrote:
>
>>
If the last new throws, you leak the memory for the first three objects.
If you _really_ need pointers at all, consider using std::auto_ptr during
initialization:

A::A() {
std::auto_ptr< obj1 dummy1 ( new obj1 );
std::auto_ptr< obj2 dummy2 ( new obj2 );
std::auto_ptr< obj3 dummy3 ( new obj3 );
std::auto_ptr< obj4 dummy4 ( new obj4 );
pobj1 = dummy1;
pobj2 = dummy2;
pobj3 = dummy3;
pobj4 = dummy4;
}


Actually, I could be seeing something correctly, but won't all your
pointers be destroyed as soon as you leave the scope of the
constructor?
Oops. That should be

pobj1 = dummy1.release();
...
Don't you either have to explicitly release the auto_ptr
(i.e. dummy1.release()) after the assignment... of if you can,
declare your pointers in your class as auto_ptrs i.e.:

/.h file
class A
{
public:
A();
~A();
private:
SomeMethod();

std::auto_ptr< obj1 myobj1;
std::auto_ptr< obj2 myobj2;
std::auto_ptr< obj3 myobj3;
std::auto_ptr< obj4 myobj4;

};

A::A()
: myobj1(new obj1),
myobj2(new obj2),
myobj3(new obj3),
myobj4(new obj4)
{
}

Of course, they do not have to be auto_ptrs I guess... but using some
type of smart pointer in the declaration may make your life easier
than just using raw pointers.
Yes.
Thanks

Kai-Uwe Bux
Jun 27 '08 #6
"tech" <na************@googlemail.comwrote in message
news:fc**********************************@p25g2000 hsf.googlegroups.com...
Hi, Whenever i have a class that contains references to other classes
i keep
end up doing the below. However it doesn't seem so safe or elegant.
How do the
pros initialise subobjects, any ideas to improve the below would be
welcome.
__________________________________________________ _________
#include <memory>
#include <cstdio>

#define PRINTF_THIS(mp_this, mp_name, mp_func) ( \
std::printf("(%p)->" # mp_name "::" # mp_func "\n", \
(void*)(mp_this)) \
)

struct obj1 {
obj1() { PRINTF_THIS(this, obj1, obj1()); }
~obj1() { PRINTF_THIS(this, obj1, ~obj1()); }
};

struct obj2 {
obj2() { PRINTF_THIS(this, obj2, obj2()); }
~obj2() { PRINTF_THIS(this, obj2, ~obj2()); }
};

struct obj3 {
obj3() { PRINTF_THIS(this, obj3, obj3()); }
~obj3() { PRINTF_THIS(this, obj3, ~obj3()); }
};

struct obj4 {
obj4() { PRINTF_THIS(this, obj4, obj4()); }
~obj4() { PRINTF_THIS(this, obj4, ~obj4()); }
};

class not_copyable {
not_copyable(not_copyable const&);
not_copyable const& operator =(not_copyable const&);
protected:
not_copyable() {}
~not_copyable() {}
};

class A : private not_copyable {
std::auto_ptr<obj1m_obj1;
std::auto_ptr<obj2m_obj2;
std::auto_ptr<obj3m_obj3;
std::auto_ptr<obj4m_obj4;

public:
A()
: m_obj1(new obj1()),
m_obj2(new obj2()),
m_obj3(new obj3()),
m_obj4(new obj4()) {
PRINTF_THIS(this, A, A());
}

~A() { PRINTF_THIS(this, A, ~A()); }
};

int main() {
{
A a;
}
std::puts("\n\n_____\npress <ENTERto exit...");
std::getchar();
return 0;
}

__________________________________________________ _________

Does that do what you want?

Jun 27 '08 #7
Thanks for all the replies, one further question

if i don't usse pointers but object members instead i need to include
the header files rather than forward declare. Isn't this an argument
against having member objects?
Jun 27 '08 #8
tech wrote:
if i don't usse pointers but object members instead i need to include
the header files rather than forward declare. Isn't this an argument
against having member objects?
Class design should not be governed by the [in]convenience of header
inclusion (with a very few exceptions, see PIMPL idiom).

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jun 27 '08 #9

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

Similar topics

9
by: relaxedrob | last post by:
Howdy All! I am still getting my head around a few base concepts. Any comments or criticisms on the below definitions would be most welcome! A function is an object. JavaScript objects have...
3
by: Hermit Crab | last post by:
I'm seeing some unexpected (at least to me) behavior in the 'window' and 'document' objects under Netscape 7.1 and Internet Explorer 6.0. When a property is added to the prototype for 'Object',...
6
by: Alfonso Morra | last post by:
I have written the following code, to test the concept of storing objects in a vector. I encounter two run time errors: 1). myClass gets destructed when pushed onto the vector 2). Prog throws a...
20
by: Brett Romero | last post by:
I'd like a variable to be created once and called statically from anywhere in the app. Is the following sufficient or will multiple instances still be created: private static SqlConnection Conn...
5
by: wshaer | last post by:
Hi This is the task: and these are my classes: public class Engine{ // Declare the varibles
14
by: Jess | last post by:
Hello, I learned that there are five kinds of static objects, namely 1. global objects 2. object defined in namespace scope 3. object declared static instead classes 4. objects declared...
167
by: darren | last post by:
Hi I have to write a multi-threaded program. I decided to take an OO approach to it. I had the idea to wrap up all of the thread functions in a mix-in class called Threadable. Then when an...
3
by: Bruno.DiStefano | last post by:
Hi All, BACKGROUND INFO I need to use a "vector" structure to store a number of objects that becomes known only at run time. The constructor, at instantiation time of a new object, increments a...
55
by: tonytech08 | last post by:
How valuable is it that class objects behave like built-in types? I appears that the whole "constructor doesn't return a value because they are called by the compiler" thing is to enable...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

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.