473,770 Members | 2,120 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Class members, pointers or not?



Is it best to declare class member objects as pointers or not pointers?

class A {
public:
A(int i);
//....
};

class B {
public:
B() : m_var(0)
{
m_var = new A(15);
}
private:
A *m_var;
};

class B {
public:
B() : m_var(15)
{
}
private:
A m_var;
};
Jul 22 '05 #1
4 1772
Oystein Haare wrote:

Is it best to declare class member objects as pointers or not pointers?
If possible, avoid pointers.

class A {
public:
A(int i);
//....
};

class B {
public:
B() : m_var(0)
{
m_var = new A(15);
}
private:
A *m_var;
};
This class is incomplete. It lacks a correct working
destructor, copy constructor and assignment operator.

class B {
public:
B() : m_var(15)
{
}
private:
A m_var;
};


This class works out of the box. The compiler generated
destructor, copy constructor and assignment operator do
the right thing.

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 22 '05 #2

Depends entirely on what the member object is and how you plan to use it.
Some considerations, using

#include "C.h" // class C
class B;
class A
{
B *b;
C c;
};

- b has to be to be explicitly constructed and destructed (new / delete),
but it can also be replaced or deleted at will:
you have full control over constructing b, as opposed to c which gets
constructed/deleted automatically when A does;
you have the extra option to have b == NULL if that makes sense, as
opposed to c which must always exist.

- you don't need a B.h header file to declare a B*, which means you don't
have to recompile A when B.h changes.

- If sizeof(C) changes, sizeof(A) changes too. Does that matter?
"Oystein Haare" <oy*****@online .no> wrote in message
news:pa******** *************** *****@online.no ...


Is it best to declare class member objects as pointers or not pointers?

class A {
public:
A(int i);
//....
};

class B {
public:
B() : m_var(0)
{
m_var = new A(15);
}
private:
A *m_var;
};

class B {
public:
B() : m_var(15)
{
}
private:
A m_var;
};

Jul 22 '05 #3
Oystein Haare wrote:

Is it best to declare class member objects as pointers or not pointers?
class B { .... public:
B() : m_var(0)
{
m_var = new A(15);
}
private:
A *m_var;
};


Pointers increase code complexity. However, in big projects,
they allow to hide the implementation and to decrease
dependencies between source files (only include declaration
of class A where it is really needed...).
Pointers also have different "const" behavior ( changing
*m_var is allowed even if the container is constant, this
helps if the mutable keyword is not supported ).
Using accessors rather than the pointer itself is safer.
Smart pointers is another possibility.

// file B.h
class A; // forward declaration
class B
{
...
private:
const A & m_var() const { return *m_var_ptr_dont _use; }
A & m_var() { return *m_var_ptr_dont _use; }
A * m_var_ptr_dont_ use;
/* direct use of this pointer should be limited to a few
member functions. A long suggesting name discourages direct
use of the pointer... */
};
Jul 22 '05 #4
Oystein Haare <oy*****@online .no> wrote in message news:<pa******* *************** ******@online.n o>...
Is it best to declare class member objects as pointers or not pointers?


Generally speaking, using pointer members (and reference members)
requires more care than regular data members. However, there are some
cases when they are useful or even unavoidable.

1) When an contained object cannot be properly created when the
constructor for the enclosing class is called, you can declare a
pointer member and then initialize it with a call to new when you have
enough information to properly create the member. Of course you had
then better properly delete the pointer in the destructor for the
enclosing class. In my experience, this is a useful solution to the
problem of creating sub-objects that require user-input to be created.

2) To avoid copying a large, already-existing object, it is sometimes
useful to use a pointer (or reference) member in a class to access the
external object. If the object will never change and is available
when the constructor is called, then use a (const) reference-member,
otherwise you have to use a pointer-member. Of course lifetime issues
then become a potentially serious problem (you don't want to try to
access the external object through the pointer/reference member after
it has been destructed), so care is required. Note that most (all?)
of the time, equivalent behavior can be achieved by passing the
external object as an argument to a member function, which is a safer
solution.

3) For separating interface and implementation in a class design, it
is sometimes useful to the so-called "pimpl-idiom" (pimpl == private
implementation) . For example,

// file "foo.hpp"

class foo {
public:
foo(int);
// whatever
private:
class pimpl; // forward declaration
pimpl* acne;
};

// file "foo.cpp"

class foo::pimpl {
int a_;
public:
pimpl(int a) : a_(a);
// private implementation
};

foo::foo(int a) {
acne = new pimpl(a);
}

// other foo member functions requiring information from foo::pimpl
This allows more "modular" C++ code, where the interface in the .hpp
file just provides users with the semantics for using the class, and
all of the implementation details and data members are hidden in the
..cpp file. So, if you decide to completely re-implement a class, you
can just replace the code in the .cpp file without changing the header
file at all. I understand that this is a particularly useful trick
when writing libraries, but that is not something I have experience
with myself.

4) anything else I have forgotten <grin>
Hope this sheds some light on things for you ...

Dave Moore
Jul 22 '05 #5

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

Similar topics

6
2472
by: lovecreatesbeauty | last post by:
Hello Experts, Why static data members can be declared as the type of class which it belongs to? Inside a class, non-static data members such as pointers and references can be declared as type of its own class. Non-static data members can not be declared as type of its own class (excluding pointers and references).
10
3334
by: Bhan | last post by:
Using Ptr of derived class to point to base class and viceversa class base { .... } class derived : public base { .... }
3
1225
by: m | last post by:
Hi, I'm reading Microsoft Visual C++ .NET Step by Step, Version 2003 and I found a sentence it says : "you can't have pointers to managed types as members of a __gc class.". Why ? Thanks, Michele
20
2129
by: Joe Van Dyk | last post by:
Is there some rule of thumb about when to use pointers to an object and when to use a reference* to an object when a class needs to have objects as data members? Example: class A { B* b_ptr; B b; vector<B*> vector_ptrs;
2
2591
by: GRenard | last post by:
Hello, We just switch in our company to VisualStudio 2005 and the new ATL library. We use a wrapper to use CFileDialog. Its name is CFileDialogDeluxe Here the call CFileDialogDeluxe oFileDialog( ... ); There are some problems in the debug, look the sizeof from the debug :
14
2644
by: lovecreatesbea... | last post by:
Could you tell me how many class members the C++ language synthesizes for a class type? Which members in a class aren't derived from parent classes? I have read the book The C++ Programming Language, but there isn't a detail and complete description on all the class members, aren't they important to class composing? Could you explain the special class behavior in detail? Thank you very much.
14
1883
by: Glen Dayton | last post by:
While looking at some old code I ran across a snippet that increments a pointer to access different members of a structure: .... struct Badness { std::string m_begin; std::string m_param1; std::string m_param2; std::string m_end;
8
2889
by: crjjrc | last post by:
Hi, I've got a base class and some derived classes that look something like this: class Base { public: int getType() { return type; } private: static const int type = 0; };
9
3465
by: Taras_96 | last post by:
Hi everyone, I was experimenting with static_cast and reinterpret cast #include <iostream> struct A1 { int a; }; struct A2 { double d; }; struct B : public A1, A2
0
9618
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
10260
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
10101
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...
0
9906
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7456
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2850
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.