Solved

constructor inside a constructor

Posted on 2004-08-01
6
380 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 39

Expert Comment

by:itsmeandnobodyelse
Comment Utility
>> 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
Comment Utility
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
Comment Utility
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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…

771 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now