Thread: should i always write a constructor for a class?

  1. #16
    Registered User
    Join Date
    Jan 2014
    Posts
    17
    Are constructors basically there to initialize data members in a class?

  2. #17
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Quote Originally Posted by jaxdid View Post
    Are constructors basically there to initialize data members in a class?
    I would say that most constructors call the constructors of its members and does nothing else. Really it depends on the object and how it is used; there may be occasions where you think you have to do something in addition to that, like write in a log, or send a message to the winproc in a WinAPI program, or something else. You always want the object to be ready to do what it is supposed to do after it is finished being initialized, and that can mean a lot of things.
    Last edited by whiteflags; 08-31-2014 at 07:35 PM.

  3. #18
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by jaxdid
    Are constructors basically there to initialize data members in a class?
    Stroustrup puts it this way: a constructor is "used to initialize objects of its class. Often used to establish an invariant for the class. Often used to acquire resources. A constructor establishes a local environment in which member functions execute."

    So, as part of the process of initialising an object of the class, the constructor would typically initialise the data members, but the scope of what initialising an object of the class means can go beyond that.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Class FILE to write in DOS encoding.
    By ArnoldRich in forum C Programming
    Replies: 5
    Last Post: 12-13-2013, 10:30 AM
  2. no default constractor ....
    By mixalissen in forum C++ Programming
    Replies: 11
    Last Post: 05-17-2008, 04:15 AM
  3. How write class like vector that deletes self?
    By 6tr6tr in forum C++ Programming
    Replies: 7
    Last Post: 05-04-2008, 11:46 AM
  4. I am trying to write a code to search a class
    By jrb47 in forum C++ Programming
    Replies: 3
    Last Post: 12-02-2006, 02:33 PM
  5. learn to write a class
    By henry in forum C++ Programming
    Replies: 14
    Last Post: 04-10-2003, 03:31 PM