Solved

constructor inside a constructor

Posted on 2004-08-01
6
391 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 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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Cross compile release version of c++ program for linux 2 147
Issues with C++ Class 19 121
Outlook 13 102
keep track of class structure 1 55
Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
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 learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

752 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