Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

constructor inside a constructor

Posted on 2004-08-01
6
Medium Priority
?
403 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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 200 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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
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…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

721 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