473,467 Members | 1,291 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

private default constructor is good or bad?

In his book "More Effective C++", Scott Meyer suggests in "Item 4" to
"Avoid gratuitous default constructors".

To summarize his claims against default constructors for "the right
classes" he states that:

================== START QUOTE =============
"A default constructor is the C++ way of saying you can get something
for nothing. Constructors initialize objects, so default constructors
initialize objects without any information from the place where the
object is being created. Sometimes this makes perfect sense. Objects
that act like numbers, for example, may reasonably be initialized to
zero or to undefined values. Objects that act like pointers may
reasonably be initialized to null or to undefined values. Data
structures like linked lists, hash tables, maps, and the like may
reasonably be initialized to empty containers.

Not all objects fall into this category. For many objects, there is no
reasonable way to perform a complete initialization in the absence of
outside information. For example, an object representing an entry in an
address book makes no sense unless the name of the thing being entered
is provided. In some companies, all equipment must be tagged with a
corporate ID number, and creating an object to model a piece of
equipment in such companies is nonsensical unless the appropriate ID
number is provided.

Inclusion of meaningless default constructors affects the efficiency of
classes, too. If member functions have to test to see if fields have
truly been initialized, clients of those functions have to pay for the
time those tests take. Furthermore, they have to pay for the code that
goes into those tests, because that makes executables and libraries
bigger. They also have to pay for the code that handles the cases where
the tests fail. All those costs are avoided if a class's constructors
ensure that all fields of an object are correctly initialized. Often
default constructors can't offer that kind of assurance, so it's best
to avoid them in classes where they make no sense. That places some
limits on how such classes can be used, yes, but it also guarantees
that when you do use such classes, you can expect that the objects they
generate are fully initialized and are efficiently implemented."
================== END QUOTE =============

Now... I tried to follow this guideline (among others), by declaring a
private default constructor for a class that seems to be useless
without being properly initialized with some values.

However, this created a problem of inability to optimize my application
for speed. The reason is that in my particular case I am re-creating a
database record (represented by the aforementioned class with private
ctor) on the heap in a pretty huge loop. The call to 'new' is very
costly in terms of CPU cycles... I realized I can improve performance
greatly if I instantiate this record only once *outside* the loop.
However, outside the loop I don't have any meaningful values to
initialize that record with, so a default constructor seems to be
required here...

So, my question is: how do I solve the dilemma? On one hand, from the
*logical correctness* point of view, it doesn't make sense for my class
to have a default constructor. On the other hand, from *performance*
point of view a default constructor is required (or using some dummy
values for the non-default ctor, which is basically the same).

Can performance considerations justify violation of "elegant
implementation"?

Dec 15 '05 #1
3 6769
Oops... Sorry for posting here. After waiting in vain the entire day
for my post to appear on comp.lang.c++.moderated, I thought my message
was rejected and thus decided to try my luck here. Interestingly
enough, a few minutes after posting here, my message appeared in
comp.lang.c++.moderated as well... I guess I should have waited longer.
Sorry again for the double-post. You can safely ignore this thread.

Dec 15 '05 #2

swengtoo wrote:
In his book "More Effective C++", Scott Meyer suggests in "Item 4" to
"Avoid gratuitous default constructors". So, my question is: how do I solve the dilemma?


First by realizing that even what seems like a logically good idea
doesn't always apply.

Second, you could implement some sort of static class that does the
optimization you want by "initializing" the same pointer with different
data. Doing this without getting ugly could get ugly. Some sort of
factory method of sorts.

Good luck.

Dec 16 '05 #3
Maybe I am missing the point here. but I will give this a try. . .

If you want to construct and not pay for the memory allocation penalty
, why not just create your object local to this function. You create a
local object and then using placement new, you can re-construct the
object over and over again, with whatever constructor. You will not
allocate any memory, and the only penalty you pay is the actual
constructor call.

I think there is some magic involved if you need to call the
onstructor. something like

Is this what you are looking for ?

-Art

#include <new>

class Foo {
public:
Foo ( int a ) : A(a) { }
private :
Foo() ;
int A ;
};

void do_some_foo ( void )
{
Foo local_foo ( -1 ) ; // Local variable
int count_a = 0 ;
while ( 1 ) {
local_foo.Foo::~Foo() ; // If you need to call this
new ( &local_foo ) Foo ( count_a++ ) ; // will not allocate
}
}

Dec 16 '05 #4

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

Similar topics

15
by: A | last post by:
Hi, A default copy constructor is created for you when you don't specify one yourself. In such case, the default copy constructor will simply do a bitwise copy for primitives (including...
34
by: Andy | last post by:
1) Is there any use of defining a class with a single constructor declared in private scope? I am not asking a about private copy constructors to always force pass/return by reference. 2) Is...
10
by: Ioannis Vranos | last post by:
May someone explain why does this compile? class HiddenSealBaseClass { public: HiddenSealBaseClass() { } }; class Sealed: virtual HiddenSealBaseClass
4
by: plmanikandan | last post by:
Is static constructor available in C++? Can anybody explain me about private and static constructors in c++ Rgds, Mani
12
by: Elad | last post by:
Hello All, Im taking an OOP course, in one of the tutorials, there was a frozen class example, i.e. a class which is impossible to inherit from, the example was something like: struct ice__ {...
3
by: John Salmon | last post by:
g++ complains about illegal access to a private member when the following is compiled with a private copy constructor for the class C. When the copy constructor is public, the program runs and...
4
by: Jess | last post by:
Hello, I tried several books to find out the details of object initialization. Unfortunately, I'm still confused by two specific concepts, namely default-initialization and...
10
by: siddhu | last post by:
Dear Experts, I want to make a class whose objects can be created only on heap. I used the following approach. class ss { ss(){} public: void* operator new(size_t sz)
7
by: Rahul | last post by:
Hi Everyone, I was trying to implement a final class and i start having the destructor of the final class as private, class A { ~A() { printf("destructor invoked\n");
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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,...
0
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...
1
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...
0
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...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.