LinuxQuestions.org
Share your knowledge at the LQ Wiki.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 08-24-2005, 03:00 AM   #1
InvisibleSniper
Member
 
Registered: Jul 2005
Location: Australia
Distribution: Debian
Posts: 113

Rep: Reputation: 15
OOP Help Please


Hi again,

I need some help understanding what constructors are for and how to implement them, as I am a bit lost trying to understand it from a book.
 
Old 08-24-2005, 03:16 AM   #2
Nylex
LQ Addict
 
Registered: Jul 2003
Location: London, UK
Distribution: Slackware
Posts: 7,464

Rep: Reputation: Disabled
Constructors are the way to create new instances of a class. They have the same name as the class and can take arguments, but they don't have to. If you do not provide a constructor, the compiler gives you a default one for free. The only thing a default constructor will do is create a new object of that class; it will not initialise any of the member variables. If you do write any constructor, a default constructor won't be provided, so if you need one that takes no arguments, you'll have to write one.

Suppose you have a class Cat and when you create a Cat, you'd like to set it's age. You can do that by adding a constructor that takes an integer parameter:

Code:
class Cat
{
        public:
           Cat(int age);
        private:
            int itsAge;
};
You could then write the implementation as

Code:
Cat::Cat(int age):itsAge(age) {}
The bit after the single colon is the initialisation stage, you can initialise any number of member variables here, separated by commas. In this example, an equivalent way of initialising itsAge would be

Code:
Cat::Cat(int age)
{
     itsAge = age;
}
Both work, but my book (and probably yours too as they're written by the same author) say you should initialise itsAge in the initialisation.

Constructors can be overloaded and all that means is, you can have multiple constructors that can take different arguments:

Code:
class Cat
{
       public:
           Cat();      // default constructor
           Cat(int age, int weight):itsAge(age), itsWeight(weight) {}
           Cat(int age) { itsAge = age; }
       private:
           int itsAge;
           int itsWeight;
};
Does that help a bit? If not, tell us which bits you aren't understanding.
 
Old 08-24-2005, 03:25 AM   #3
IBall
Senior Member
 
Registered: Nov 2003
Location: Perth, Western Australia
Distribution: Ubuntu, Debian, Various using VMWare
Posts: 2,088

Rep: Reputation: 62
Constructors are used to create an object, and (usually) to do some initialisation. They have the same name as the class, and are called when you create a new object.

For example, using Java:
Code:
Date d = new Date();
Where I have a Date class, and I want an instance of it called d. The above statement will call the default constructor:
Code:
public class Date
{
//First some variables
private int dayOfWeek;
private int weekOfYear;
private int year;

//And the default constructor
public void Date()
    {
     dayOfWeek=0;
     weekOfYear=0;
     year=0;
     }
}
You can have other constructors that take arguments, such as values to store in the Date Class

I hope this helps (It was done by memory )
--Ian

Last edited by IBall; 08-24-2005 at 03:30 AM.
 
Old 08-24-2005, 03:33 AM   #4
IBall
Senior Member
 
Registered: Nov 2003
Location: Perth, Western Australia
Distribution: Ubuntu, Debian, Various using VMWare
Posts: 2,088

Rep: Reputation: 62
Quote:
Originally posted by Nylex
If you do not provide a constructor, the compiler gives you a default one for free. The only thing a default constructor will do is create a new object of that class; it will not initialise any of the member variables.
It has been well drilled in to me that you ALWAYS INITIALISE VARIABLES. Never trust a compiler to do it for you, since if you initialise them, you know what is stored there. This is particularly so with C / C++, since not all compilers are the same.

--Ian
 
Old 08-24-2005, 05:31 AM   #5
InvisibleSniper
Member
 
Registered: Jul 2005
Location: Australia
Distribution: Debian
Posts: 113

Original Poster
Rep: Reputation: 15
Quote:
Originally posted by IBall
It has been well drilled in to me that you ALWAYS INITIALISE VARIABLES. Never trust a compiler to do it for you, since if you initialise them, you know what is stored there. This is particularly so with C / C++, since not all compilers are the same.

--Ian
You mean because some compilers may put whatever was in the memory address before you defined the varialbe into the variable?
 
Old 08-24-2005, 05:34 AM   #6
Nylex
LQ Addict
 
Registered: Jul 2003
Location: London, UK
Distribution: Slackware
Posts: 7,464

Rep: Reputation: Disabled
Yeah, that's what he means. I don't think it's some compilers though, I think it's all of them.
 
Old 08-24-2005, 03:19 PM   #7
InvisibleSniper
Member
 
Registered: Jul 2005
Location: Australia
Distribution: Debian
Posts: 113

Original Poster
Rep: Reputation: 15
Some things I don't understand about this are:
  • If I take out the (5) parameter in Cat Frisky(5); it doesn't compile, how come?
  • So a constructor is just another accessor function that lets you free up the memory when you have finished?
  • I would like to learn a bit more about constructors before I go on to the next chapter, does anyone know of any good resourses/tutorials on constructors and deconstructors?
  • Also what would be the syntax of declaring and then defining a class method that was inline and const?



This below is the include file:
Code:
#include <iostream>

using namespace std;


 class Cat

 {

 public:

     Cat (int initialAge);

     ~Cat();

     int GetAge() { return itsAge;}             // inline!

     void SetAge (int age) { itsAge = age;}     // inline!

     void Meow() {cout << "Meow.\n";}     // inline!

 private:

    int itsAge;

 };
And this here is the .cpp source file:
Code:
#include "CAT.hpp"


Cat::Cat(int initialAge){  //constructor
itsAge = initialAge;
}
 Cat::~Cat()
 {
 }
 //Create a cat, set its age have it meow tell us its age then meow again.
 int main()
 {
 Cat Frisky(5); //Create Frisky the cat, which is an instance of the
 //cat class.

 Frisky.Meow();//Have it meow

 cout<<"Frisky is a cat who is ";
 cout<<Frisky.GetAge();
 cout<< " years old.\n";
 Frisky.Meow();
 Frisky.SetAge(7);
 cout<<"Now Frisky is ";
 cout<<Frisky.GetAge()<< " years old.\n";
 cin.get();
 cin.get();
 cin.get();
 return (0);
}
 
Old 08-24-2005, 08:20 PM   #8
IBall
Senior Member
 
Registered: Nov 2003
Location: Perth, Western Australia
Distribution: Ubuntu, Debian, Various using VMWare
Posts: 2,088

Rep: Reputation: 62
Quote:
If I take out the (5) parameter in Cat Frisky(5); it doesn't compile, how come?
You don't have a default constructor. If you try to create an object without passing arguments to the constructor you have, it won't compile because it is expecting an argument.

It is "Good Programming Practice" to always have a default constructor, even if you don't intend to use it. I have modified your program to include a defualt constructor, and create two Cat Objects, one using the default constructor, and the other taking itsAge as an argument.

The header file:
Code:
#include <iostream>

using namespace std;


 class Cat

 {

 public:

     Cat();
     Cat(int initialAge);

     ~Cat();

     int GetAge() { return itsAge;}             // inline!

     void SetAge (int age) { itsAge = age;}     // inline!

     void Meow() {cout << "Meow.\n";}     // inline!

 private:

    int itsAge;

 };
And the code.
Code:
#include "cat.hpp"

/*This defines the constructors*/
Cat::Cat( void)
    {
    itsAge=0;
    }

Cat::Cat(int initialAge)
    {
    itsAge = initialAge;
    }

 Cat::~Cat()
 {
 }

 //Create a cat, set its age have it meow tell us its age then meow again.
 int main()
 {
 /*Create too cats, one Frisky, one Cuddles :)*/
 Cat Frisky; 
 Cat Cuddles(5);

 Frisky.Meow();//Have it meow

 cout << "Frisky is a cat who is " << Frisky.GetAge() << " years old.\n";
 Frisky.Meow();
 Frisky.SetAge(7);
 cout<<"Now Frisky is " << Frisky.GetAge() << " years old.\n";

 cout <<"Cuddles is a cat who is :" << Cuddles.GetAge() << "years old.\n";
 Cuddles.Meow();
 Cuddles.SetAge(23);
 cout<<"Now Cuddles is " << Cuddles.GetAge() << " years old.\n";

 return (0);
}
I hope this helps
--Ian

Last edited by IBall; 08-24-2005 at 08:21 PM.
 
Old 08-25-2005, 10:36 AM   #9
addy86
Member
 
Registered: Nov 2004
Location: Germany
Distribution: Debian Testing
Posts: 332

Rep: Reputation: 31
Since you are learning C++, I can only recommend these two sites:
C++ Annotations
C++ FAQ Lite
 
Old 08-25-2005, 10:59 AM   #10
InvisibleSniper
Member
 
Registered: Jul 2005
Location: Australia
Distribution: Debian
Posts: 113

Original Poster
Rep: Reputation: 15
Can you tell me what this statement would be used for in a real program Cat Cuddles(5);. With the Cuddles(5) does that mean that you actually assigned 5 to the object?

I mean why would I want to do that if I was making a real program?
 
Old 08-25-2005, 10:59 AM   #11
Nylex
LQ Addict
 
Registered: Jul 2003
Location: London, UK
Distribution: Slackware
Posts: 7,464

Rep: Reputation: Disabled
Quote:
Originally posted by InvisibleSniper
  • Also what would be the syntax of declaring and then defining a class method that was inline and const?
Code:
class className
{
        public:                        // assuming you wanted public access to it
             return_type method_name(parameters) const { // do stuff }
}
Quote:
Originally posted by InvisibleSniper
Can you tell me what this statement would be used for in a real program Cat Cuddles(5);. With the Cuddles(5) does that mean that you actually assigned 5 to the object?
He has a constructor that takes an int and uses that int to set the Cat's age. The statement "Cat Cuddles(5);" says make a new Cat and set his age to 5. You can see that in the implementation of the constructor:

Code:
Cat::Cat(int initialAge)
    {
    itsAge = initialAge;
    }

Last edited by Nylex; 08-25-2005 at 11:03 AM.
 
Old 08-25-2005, 11:07 AM   #12
InvisibleSniper
Member
 
Registered: Jul 2005
Location: Australia
Distribution: Debian
Posts: 113

Original Poster
Rep: Reputation: 15
Can someone tell me how the name constructor was given?

I mean I can declare an object of Cat by just going
Code:
object Cat;
why would I want to go
Code:
Cat();
then
Code:
 ~Cat();
then have to define it all?
 
Old 08-25-2005, 11:32 AM   #13
Nylex
LQ Addict
 
Registered: Jul 2003
Location: London, UK
Distribution: Slackware
Posts: 7,464

Rep: Reputation: Disabled
Not quite sure what you're asking. The constructor name is the same as the name of the class. If you want to make an object of type Cat, you'd write "Cat" followed by any legal variable name, so for example, Cuddles is fine.

Code:
Cat Cuddles;
The constructor and destructor go in the class definition, eg.

Code:
class Cat
{
       public:
            Cat();
            ~Cat();
        
       // other stuff
};
If you do declare them like this, then you have to write a definition as in

Code:
Cat::Cat()
{
    // code here
}
If you do not want to use any statements in the body of the constructor/destructor, you can just use

Code:
class Cat
{
       public:
           Cat() {}
           ~Cat() {}
      
       // other stuff
};
 
Old 08-26-2005, 04:56 AM   #14
InvisibleSniper
Member
 
Registered: Jul 2005
Location: Australia
Distribution: Debian
Posts: 113

Original Poster
Rep: Reputation: 15
So a contructor, put simply initilizes an object? I mean I can use an accessor function to initilise variables without using a constructor, so why would I want to use a constructor?
 
Old 08-26-2005, 07:18 PM   #15
InvisibleSniper
Member
 
Registered: Jul 2005
Location: Australia
Distribution: Debian
Posts: 113

Original Poster
Rep: Reputation: 15
Sorry for double posting but can someone tell me what the big advantage is of using a constructor other then using a accessor function?
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
OOP in PHP patpawlowski Programming 5 11-20-2005 04:37 PM
What is true OOP? tumana Programming 4 09-13-2004 06:51 AM
Why use OOP when OBP will do? unholy Programming 2 08-27-2004 04:56 PM
When to use OOP KptnKrill Programming 10 08-24-2003 01:15 PM
newbie oop Isitme Programming 3 10-10-2001 12:48 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 06:47 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration