Constructor problem

Started by
21 comments, last by pdstatha 22 years, 3 months ago
name = new string("Whatever") will absolutely not work since name is of type string , while new always returns a pointer to the object it creates. Plus, you'd then have to remember to use delete on name , presumably in the destructor.

If you want to initialize any object upon its construction in your constructor, just call its contructor in the class contructor initialization list:
    class blah{    public:        blah():            name("Hello, world"), stuff(12.0f)            {}    private:        string name;        float stuff;};  


It just so happens that both string and float have operator= overloaded, so you can also assign to them like this (what you're used to):
  class blah{    public:        blah()        {            name = "Hello, world";            stuff = 12.0f;        }    ...}  


Although these are essentially equivalent, they're literally not. In the second example, both name and stuff have been constructed with their default constructors. So, the only way to truly "initialize" those objects as they're constructed is to call their constructors. And, of course, you can only do that when the objects themselves get constructed. But inside the body of the constructor, those objects have already been constructed, which is what initialization lists are for: to give you the chance to construct as they're constructed.

One thing that'll get you into some serious trouble, having come from a Java background, is excessive use of new . As a rule, you rarely have to use new , except for when you'll only know how many items to allocate at runtime. Otherwise, use standard static allocation. In the case of classes, structs, and unions, every member you declare is stack-allocated, so never try to use new to allocate them.

Edited by - merlin9x9 on January 4, 2002 8:26:01 AM
Advertisement
Thats fine for a string, but what about for an object that has been user defined such as in my Product class. Eg.

      class Tray{    public:		Tray(const char* itsCode = "", const Product* trayItem)://'Tray::Tray' : missing default parameter for parameter 2		  code(itsCode), prod()		  {}        Tray(const string& itsCode, const Product& trayItem): 		  limit(20), quantity(20), code(itsCode), prod(trayItem)		  {}		  // I'm guessing that you don't need a deconstructor here, either		  const string& getCode() const {return code;}		  const Product& getProduct() const {return prod;}		  int getQuant() const {return quantity;}		  void dispense() {--quantity;}	private:        int limit;        int quantity;        string code;        Product prod;};  


Obviously I have to intialise the Product in the constructor but I thought I was doing this by here.

        ):  code(itsCode), prod()      



Edited by - pdstatha on January 4, 2002 8:43:46 AM

Edited by - pdstatha on January 4, 2002 8:44:59 AM
The same applies for all types, both built-in and user-defined.

All members will be constructed no matter what (you'd never be able to use them, otherwise). In other words, you don't have to explicitly initialize/construct them using the initializer list. So, since you're using the Product 's default constructor in Tray::Tray for prod , there's no need to specify an empty argument list; you can omit prod from the initializer list altogether. This is because, again, members are constructed no matter what you do, and the only time objects' default constructors are not called is when you use one of their other constructors in an initializer list.

Here's an example. This...
    class hello{    public:        hello(int val = 144):            x(val)            {}    private:        int x;};class blah{    public:        blah():            a(), b(12)            {}    private:        hello a;        int b;};  

...is exactly equivalent to...
  class hello{    public:        hello(int val = 144):            x(val)            {}    private:        int x;};class blah{    public:        blah():            b(12)            {}    private:        hello a;        int b;};  


In the example, having omitted the imitialization of a with an empty argument list will result in a containing a value of 144 for its x member. If you wanted that member to be set to something other than 144—the default—on construction, then you would have to put a in the initializer list, specifying the desired value as the parameter.

Of course, you can put the empty argument list and all of that in there if it makes you more comfortable with what's going on, but it's not necessary.

Edited by - merlin9x9 on January 4, 2002 11:36:25 AM

This topic is closed to new replies.

Advertisement