Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

constructor inside a constructor

Posted on 2004-08-01
6
Medium Priority
?
405 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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
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

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Question has a verified solution.

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

Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
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 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.
Suggested Courses
Course of the Month13 days, 8 hours left to enroll

963 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