Solved

constructor inside a constructor

Posted on 2004-08-01
6
384 Views
Last Modified: 2010-04-01
Can I create a constructor inside an other constructor, by passing the parameters of the first constructor to the second constructor

Sample code:

Reservation::Reservation(Trucks* tptr, Customer* cptr)
{
      cout<<"\nEnter Reservation date";
      cin>>Res_Date;//overloading required
      cout<<"\nEnter Pick Date";
      cin>>Pick_Date;
      cout<<"\nEnter Reservation id";
      cin>>Res_Id;
      cout<<"\nEnter the contract time period";
      cin>>Contract;
      cout<<"\nEnter VIN number";
      cin>> (tptr->VIN);
      cout<<"\nEnter License number";
      cin>>(cptr->Licence_No);
//////////now passing these values to create a onject
Reservation R=new Reservation(Res_Date,Pick_Date, Res_Id,Contract,tptr->VIN,cptr->Licence_No);
}
0
Comment
Question by:rmvprasad
6 Comments
 
LVL 17

Expert Comment

by:rstaveley
ID: 11691094
Yes, it works. You'll need to meake sure that the ctor(s) that don't create a new R initialise it as NULL to make the dtor work.

Illustration:
--------8<--------
#include <iostream>
using std::cout;

class foo {
      foo *p;
public:      foo() : p(0) {
            std::cout << "ctor()\n";
      }
      foo(int) : p(new foo) {
            std::cout << "ctor(int)\n";
      }
      ~foo() {
            std::cout << "dtor (p=" << static_cast<void*>(p) << ")\n";
            delete p; // Deleting a NULL pointer is OK per the standard
      }
};

int main()
{
      foo p(1);
}
--------8<--------
0
 
LVL 4

Expert Comment

by:bkfirebird
ID: 11691102
The parameters of the second constructor seem to be different from the first one ...... in that case it should not be a problem
0
 
LVL 17

Expert Comment

by:rstaveley
ID: 11691104
BTW... Be careful about copy ctors and the assignment operator. Probably you ought to make them private to avoid having to think about them.
0
VMware Disaster Recovery and Data Protection

In this expert guide, you’ll learn about the components of a Modern Data Center. You will use cases for the value-added capabilities of Veeam®, including combining backup and replication for VMware disaster recovery and using replication for data center migration.

 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 11691506
>> Can I create a constructor inside an other constructor
>> Yes, it works.

I got the impression that question and answers talk of two different things:

If you want to implement one constructor by calling a second constructor like that:

class A
{
   int m_i;
public:
   A(bool b) { m_i = b? 1 : 0; }
   A(int i) : A(false) {}  
};

you'll get an error 'illegal member initialization: 'A' is not a base or member'.

So, you could only use another constructor to construct the 'this' object by using a baseclass constructor.

Regards, Alex
0
 
LVL 2

Accepted Solution

by:
sonstkeiner earned 50 total points
ID: 11691962
The way you coded it should compile but probably does not do what you want it to do.
Assuming that you want the result of calling Reservation(trucks, customer) to be the value of 'R' (the result of the inner constructor call), your code will not work as expected, as the "outer" constructor will always refer to 'this', not to 'R' (and R would be leaked, never to be deleted).  If you absolutely wanted it to work, you would have to add this at the end:

*this= *R; delete R;

However, a simpler solution can be used here.
Write you constructor such that you pass it all the parameters it needs to construct a Reservation.
All member variables can then usually be initialized in the initialization list.

/** Initializes all Reservation fields with the given parameters. */
Reservation::Reservation(
 Res_Date_t const & rd, Pick_Date_t const & pd, Res_Id_t const & rid,
 Contract_t const & ctr, Trucks const *const tptr, Customer const *const cptr)
 :
 Res_Date(rd), Pick_Date(pd), Res_Id(rid), Contract(ctr), VIN(tptr->VIN), License_No(cptr->License_No)
{ }

This constructor lets you initialize your Reservation objects in one line, regardless of how you got the parameters.
Then write a separate function that collects all info required, then calls the constructor and returns the constructed object.
For example:

static Reservation::input(istream &, trucks, customer) { ... }

The body of that function will look very much like your constructor body, with a 'return R' at the end.
The final call would then look like this:

Reservation * R= Reservation::input(cin, trucks, customer);
0
 
LVL 2

Expert Comment

by:sonstkeiner
ID: 11723613
Oops, forgot to state input's return type, but you probably noticed that (Reservation *, of course).
Thanks fo accepting the answer anyway (;-).
0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Converting to C# also VS2015 5 125
C Language combined operators 28 109
Move constructor only called if marked noexcept? 6 104
Which Linux flavors will this run on? 6 88
Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question