Topic: Argument to constructor when declaring pointer to an object.


Author: Pete Becker <petebecker@acm.org>
Date: 1997/11/09
Raw View
TELLIS JACQUELINE wrote:
>
> I have a problem in C++ : If I create a class with a constructor that
> takes an int argument, and if I declare a pointer to this class, how will
> the constructor get called? i.e how do I pass my int argument?
>
> e.g.
>
> Class myClass
> {
>         public:
>                 myClass(int i)
>                 {
>                 }
> }
>
> myClass *clsPtr, clsVar(1);
>
> clsPtr=new myClass[1];
>
> in the above code, while declaring clsVar, I pass 1 as an argument to the
> constructor.  How do I do this in the case of the object referenced by
> clsPtr?  What happens when I declare *clsPtr?

This is a little tricky: the new expression in the code example actually
creates an array of one object. When you create an array you cannot
specify constructor arguments: the compiler will use the default
constructor. However, when you want to create a single object, you don't
need to use the array syntax.

clsPtr = new myClass;  // uses default constructor
clsPtr = new myClass(1); // uses myClass(int)

Note also that you must match the form of delete that you use to the
form of new that you used:

clsPtr = new myClass[1]; // array new
delete [] clsPtr;  // array delete

clsPtr = new myClass;  // ordinary new
delete clsPtr;   // ordinary delete

clsPtr = new myClass(1); // ordinary new
delete clsPtr;   // ordinary delete
---
[ comp.std.c++ is moderated.  To submit articles: try just posting with      ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu         ]
[ FAQ:      http://reality.sgi.com/employees/austern_mti/std-c++/faq.html    ]
[ Policy:   http://reality.sgi.com/employees/austern_mti/std-c++/policy.html ]
[ Comments? mailto:std-c++-request@ncar.ucar.edu                             ]





Author: TELLIS JACQUELINE <tellis@giasbma.vsnl.net.in>
Date: 1997/11/09
Raw View
I have a problem in C++ : If I create a class with a constructor that
takes an int argument, and if I declare a pointer to this class, how will
the constructor get called? i.e how do I pass my int argument?

e.g.

Class myClass
{
 public:
  myClass(int i)
  {
  }
}

myClass *clsPtr, clsVar(1);

clsPtr=new myClass[1];


in the above code, while declaring clsVar, I pass 1 as an argument to the
constructor.  How do I do this in the case of the object referenced by
clsPtr?  What happens when I declare *clsPtr?

Philip Tellis.
---
[ comp.std.c++ is moderated.  To submit articles: try just posting with      ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu         ]
[ FAQ:      http://reality.sgi.com/employees/austern_mti/std-c++/faq.html    ]
[ Policy:   http://reality.sgi.com/employees/austern_mti/std-c++/policy.html ]
[ Comments? mailto:std-c++-request@ncar.ucar.edu                             ]