Class Constructor question

This is a discussion on Class Constructor question within the C++ Programming forums, part of the General Programming Boards category; for example: .h file class myClass { public: myClass(); int getmydata(); void setmydata(int); ~myClass(); private: int myData; }; .cpp file ...

  1. #1
    Registered User
    Join Date
    Aug 2001
    Location
    Fort Worth, TX
    Posts
    53

    Question Class Constructor question

    for example:
    .h file
    class myClass
    {

    public:
    myClass();
    int getmydata();
    void setmydata(int);
    ~myClass();
    private:
    int myData;
    };

    .cpp file

    inlcude

    myClass::myClass()
    {
    do stuff;
    }


    question?

    How does the constructer react the following?

    myClass *mc = new myClass();

    and

    myClass mc; // will this call the constructor??

  2. #2
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,786
    In both cases, the constructor will be called.

  3. #3
    Registered User
    Join Date
    Aug 2001
    Location
    Fort Worth, TX
    Posts
    53
    what if I had a constructor that need a variable passed to it?

  4. #4
    Unregistered
    Guest
    You can have parameters in a constructor if thats what you mean. Then, you will have to use the new keyword like this:

    Code:
    CClass1*  class = new CClass1(parameters...);
    that's it.

  5. #5
    ¡Amo fútbol!
    Join Date
    Dec 2001
    Posts
    2,136
    Just overload the constructor.

  6. #6
    Registered User
    Join Date
    May 2002
    Posts
    63
    It is a good idea to overload the constructor, because if you create an instance of the class that doesn't need any arguments then there will be not constructor. Another way if you don't overload it is to give it defualt arguments.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with FIFO QUEUE
    By jackfraust in forum C++ Programming
    Replies: 23
    Last Post: 04-03-2009, 08:17 AM
  2. Class design problem
    By h3ro in forum C++ Programming
    Replies: 10
    Last Post: 12-19-2008, 08:10 AM
  3. Defining derivated class problem
    By mikahell in forum C++ Programming
    Replies: 9
    Last Post: 08-22-2007, 02:46 PM
  4. matrix class
    By shuo in forum C++ Programming
    Replies: 2
    Last Post: 07-13-2007, 01:03 AM
  5. Abstract class problem
    By VanJay011379 in forum C++ Programming
    Replies: 9
    Last Post: 07-31-2002, 01:30 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21