Help With pointers in classes.

This is a discussion on Help With pointers in classes. within the C++ Programming forums, part of the General Programming Boards category; I need a little help on understanding when pointers are involved in classes. Here is an example code. Code: // ...

  1. #1
    Ethernal Noob
    Join Date
    Nov 2001
    Posts
    1,901

    Help With pointers in classes.

    I need a little help on understanding when pointers are involved in classes. Here is an example code.
    Code:
    // Listing 8.10
    // Using pointers with const methods
    
    #include <iostream>
    using namespace std;
    
    
    class Rectangle
    {
    public:
    	Rectangle();
    	~Rectangle();
    	void SetLength(int length) {itsLength = length;}
    	int GetLength() const {return itsLength;}
    	void SetWidth(int width) {itsWidth = width;}
    	int GetWidth() const { return itsWidth;}
    
    private:
    	int itsLength;
    	int itsWidth;
    
    };
    
    Rectangle::Rectangle()
    {
    	itsWidth = 5;
    	itsLength =10;
    }
    
    Rectangle::~Rectangle()
    {}
    
    int main()
    {
    	Rectangle* pRect = new Rectangle;
    	const Rectangle * pConstRect = new Rectangle;
    	Rectangle * const pConstPtr = new Rectangle;
    
    	cout << "pRect width: " << pRect->GetWidth()
    		<< " feet\n";
    	cout << "pConstRect width: " << pConstRect->GetWidth()
    		<< " feet\n";
    	cout << "pConstPtr width: " << pConstPtr ->GetWidth()
    		<< " feet\n";
    
    	pRect->SetWidth(10);
    	// pConstRect->SetWidth(10);
    	pConstPtr->SetWidth(10);
    
    	cout << "[Rect width: " << pRect->GetWidth()
    		<< "feet\n";
    	cout << "pConstRect width: " << pConstRect->GetWidth()
    		<< " feet\n";
    	cout << "pConstPtr width: " << pConstPtr->GetWidth()
    		<< " feet\n";
        
    
    	return 0;
    
    }
    I am wondering about the lines:
    Code:
    Rectangle* pRect = new Rectangle;
    const Rectangle * pConstRect = new Rectangle;
    Rectangle * const pConstPtr = new Rectangle;
    Do they mean that basically instead of declaring an object as :
    Code:
    rectangle pRect;
    and so on, it just declares the object as a pointer? It is a little confusing to me when the difference operator is involved. Also, I am not too clear as to the use of new keyword.

  2. #2
    Registered User
    Join Date
    Nov 2001
    Posts
    1,348
    Speaking from your perception, pointers and the new instruction gives you absolute control. For example, using new, you could allocate memory for a Rectangle object and delete it later at any point in the program.

    Code:
    // In this function, rec will get destroyed after the function returns.
    void func()
    {
    Rectangle rec;
    ...
    }
    
    // In thisfunction, pRec will NOT be destroyed pass function scope.
    void func()
    {
    Rectangle *pRec = new Rectangle;
    ...
    }
    
    // Note pRec still exists.
    Kuphryn

  3. #3
    Ethernal Noob
    Join Date
    Nov 2001
    Posts
    1,901
    oh I see. 1So basically what
    Code:
    Rectangle *pRec = new Rectangle;
    is saying is creating an object that is of the class Rectangle and is also a pointer to a new location in Rectangle?

    just how it is worded is what i need clarified, also about the.

  4. #4
    Veni Vidi Vice
    Join Date
    Aug 2001
    Posts
    343

    I am wondering about the lines:
    Code:
    Rectangle* pRect = new Rectangle;
    const Rectangle * pConstRect = new Rectangle;
    Rectangle * const pConstPtr = new Rectangle


    The difference between the above declarations and
    Code:
    rectangle pRect;
    is that the first 3 declaration allocates memory dynamicly and in the second code fragment it is a static memory allocation. What does static and dynamic allocation mean??? Static declaration means that all objects are allocated at compile-time and dynamic declaration mean that objects is allocated at run-time (during program execution).


    Also, I am not too clear as to the use of new keyword.


    When you use the new keyword in your code it allocates memory(dynamic) on the free store ( or heap) and returns an address. Because objects on the free store are unnamed we have to use a pointer(s) to acces that part of memory. It is very important that we deallocate that part of memory or else we have created a memory leak.

    Example code
    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    //normal static declaration
    int inumber = 20;
    
    //This is not good, allocated dynamic memory but don't have access to it, memory leak
    //new int(10);
    
    //This is better
    int *pint = new int(10);
    //Clean up after you, avoid memory leak
    delete pint;
    return 0;
    }

  5. #5
    Ethernal Noob
    Join Date
    Nov 2001
    Posts
    1,901
    oh I see. 1So basically what
    Code:
    Rectangle *pRec = new Rectangle;
    is saying is creating an object that is of the class Rectangle and is also a pointer to a new location in Rectangle?

    just how it is worded is what i need clarified.
    Last edited by indigo0086; 10-09-2002 at 05:39 PM.

  6. #6
    Veni Vidi Vice
    Join Date
    Aug 2001
    Posts
    343
    Let me clairify it more

    Code:
    Rectangle *pRec;
    This declares a pointer to point to type Rectangle. Because itīs uninitialized it points to something (DANGEROUS)

    Code:
    Rectangle *pRec = new Rectangle;
    This does the exact same thing and initialize the pointer to a Rectangle-object (or rather the address) on the free store. If Rectangle is a user defined object itīs corresponing constructors are invoked (triggered by new).

    I hope that I donīt confuse you!

  7. #7
    Ethernal Noob
    Join Date
    Nov 2001
    Posts
    1,901
    not too confusing, so basically when pointing like
    Code:
    Rectangle *pRec;
    since it is not declared, it is not pointing to a specified address. And what did you mean by
    If Rectangle is a user defined object itīs corresponing constructors are invoked (triggered by new).

  8. #8
    Registered User
    Join Date
    Nov 2001
    Posts
    1,348
    When the pointer is first declared it does not point to anything specific. Thus you should always point to NULL.

    int *pNum = NULL;

    The key to understanding pointers is knowing that pointers refer directly to memory addresses or to other pointers. That is what pointers so powerful.

    Kuphryn

  9. #9
    Veni Vidi Vice
    Join Date
    Aug 2001
    Posts
    343

    And what did you mean by

    If Rectangle is a user defined object itīs corresponing constructors are invoked (triggered by new).


    When you create a class (like yours Rectangle), all objects of that class are called user defind objects and every time you create such an object the constructor is invoked. And likewise when an object is deleted the destructor is invoked. This all is done implicity (automatic), so you donīt have to invoke them.

    This is the construtor
    Code:
    Rectangle::Rectangle()
    {
    	itsWidth = 5;
    	itsLength =10;
    }
    And this is the destructor
    Code:
    Rectangle::~Rectangle()
    {}
    The keyword new creates an object (dynamicly).

  10. #10
    Ethernal Noob
    Join Date
    Nov 2001
    Posts
    1,901
    so by saying
    Code:
    Rectangle* pRect = new Rectangle;
    as opposed to saying
    Code:
     Rectangle myRect;
    you are saying that pRect is a pointer to a Newly assigned address of the Rectangle class?

  11. #11
    Registered User
    Join Date
    Oct 2002
    Posts
    32
    First, lose the barrier between the datatype you created (rectangle) and any other datatype. They are all just datatypes and pointers work the same for all of them.

    int *intPtr = new int;
    char *charPtr = new char;
    foo *fooPtr = new foo ();

    Another idea to get into your mind. A pointer is a datatype, it's purpose is to hold a memory address.

    The keyword "new" allocates the amount of memory needed for the datatype you are instantiating.

    fooPtr = new foo (); // we are assigning fooPtr the memory address of the new foo object.

    To access the object you need to dereference it by using the *

    *fooPtr->FooPrintMethod ();

    fooPtr->FooPrintMethod (); // bad!...you'll get yelled at by the compiler
    *fooPtr->FooPrintMethod (); // good!

    Make anymore sense?

  12. #12
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    Code:
    class Rectangle
    {
      public:
         Rectangle ();
         Rectangle (int, int);
         int width;
         int length;
    };
    
    Rectangle::Rectangle()
    {
      width = 0;
      length = 0;
    }
    
    Rectangle::Rectangle(int w, int len)
    {
      width = w;
      lenght = len;
    }
    Using above class:
    Rectangle rect; //declares on object called rect of type Rectangle with memory for rect allocated on the project stack using static memory using the default constructor. Width and lenght are bothassigned 0; This could also be written as this:
    REctangle rect();

    Rectangle rect1(3, 4);//declares an object called rect1 of type Rectangle with memory for rect1 allocated on the project stack using static memory using the constructor with two ints for arguments. Width is assigned w, 3 in this case, and length is assigned len, 4 in this case.

    Rectangle * pRect;//declares a pointer to type Rectangle called pRect. It is pointing to something, but who know what. Using pRect as it is is dangerous because we don't know what it is pointing to.

    Rectangle * pRect = NULL; //now pRect is pointing to a gauranteed memory spot called NULL. You can't use this memory spot for anything, but at least now pRect is not pointing to something it's not supposed to be pointing to.

    Rectangle * pRect = &rect; //this time pRect is declared and initialzed to the address of rect.

    Rectangle * pRect = new Rectangle;//now pRect is pointing to memory allocated on the heap(heap is also called free store and dynamic memory) for an object of type Rectangle. The object is declared using the default constructor. It could also be written like this:
    Rectangle * pRect = new Rectangle();

    Rectangle * pRect = new Rectangle(3, 4);//now pRect is pointing to memory allocated on the heap for an object of type Rectangle that is constructed using the two int constructor.

    const Rectangle rect(3, 4);//now the value of rect can not be changed from width of 3 and lenght of 4

    From here on out I _hope_ I get it correct. If not I'm sure someone will help out.

    The various possible uses of keyword const with pointers:
    const Rectangle * pRect;
    Rectangle * const pRect1;
    const Rectangle * const pRect;

    pRect is a pointer to a constant Rectangle. The value of width and length in the Rectangle that is being pointed to can't be changed.

    pRect1 is a constant pointer to a Rectangle. The value of width and length can be changed, but pRect1 can't point to anything else but the address it is pointing to.

    pRect2 is a constant pointer to a constant Rectangle. The value of width and length in the Rectangle that is being pointed to can't be changed, and pRect2 can't be changed to point to anything else.

    You can use all the flavors of keyword const noted above with dynamic memory (ie with the new keyword) just as you can non-constant pointers, etc.

    And, last, but not least, to access public members for an object from outside the class you would use the dot operator like this:

    Rectangle rect(3, 4);
    cout << rect.width << ',' << rect.length;

    and for a pointer to rect, irrespective of whether pointer is pointing to static or dynamic memory;

    Rectangle * pRect = &rect;
    cout << (*pRect).width << ','; //using dereference and dot operatorin combination
    cout << pRect->length;//using arrow operator


    Phewwwwww......
    Last edited by elad; 10-10-2002 at 01:44 PM.

  13. #13
    Veni Vidi Vice
    Join Date
    Aug 2001
    Posts
    343
    indigo0086

    Yes!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. problem with classes and pointers
    By Akkernight in forum C++ Programming
    Replies: 18
    Last Post: 02-21-2009, 06:21 AM
  2. Class with pointers to other classes as member data.
    By Sclorch in forum C++ Programming
    Replies: 2
    Last Post: 02-09-2009, 05:59 AM
  3. Pointers, Classes, and Errors o my!
    By Scottc1988 in forum C++ Programming
    Replies: 12
    Last Post: 03-13-2003, 10:14 PM
  4. Pointers to classes
    By Unregistered in forum C++ Programming
    Replies: 11
    Last Post: 06-02-2002, 10:25 PM
  5. question time (classes and pointers)
    By swarm in forum C++ Programming
    Replies: 1
    Last Post: 02-20-2002, 11:33 AM

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