Pointer to class?

This is a discussion on Pointer to class? within the C++ Programming forums, part of the General Programming Boards category; Really basic question: I'm just wondering how you use a class in an external function, here's the relevant code I've ...

  1. #1
    Registered User
    Join Date
    Jan 2002
    Location
    Vancouver
    Posts
    2,220

    Pointer to class?

    Really basic question:
    I'm just wondering how you use a class in an external function, here's the relevant code I've tried, but which obviously, doesn't work:

    Code:
    Lf::Lf(int x, int y, Grid *mygrid)
    {
       mygrid.addGridEntity(x, y, 'o');
    }
    
    int main()
    {
       Grid mygrid;
       Lf mylf(3, 3, &mygrid);
       mygrid.printGrid();
    }

  2. #2
    Programming Sex-God Polymorphic OOP's Avatar
    Join Date
    Nov 2002
    Posts
    1,078
    you can either use pointers:

    Code:
    Lf::Lf(int x, int y, Grid* mygrid)
    {
       mygrid->addGridEntity(x, y, 'o'); // use arrow not dot when dealing with a pointer
    }
    
    int main()
    {
       Grid mygrid;
       Lf mylf(3, 3, &mygrid);
       mygrid.printGrid();
    }
    or references

    Code:
    Lf::Lf(int x, int y, Grid& mygrid)
    {
       mygrid.addGridEntity(x, y, 'o'); // use dot with a reference
    }
    
    int main()
    {
       Grid mygrid;
       Lf mylf(3, 3, mygrid); // address is taken implicitly with reference initialization
       mygrid.printGrid();
    }

  3. #3
    Registered User
    Join Date
    Jan 2002
    Location
    Vancouver
    Posts
    2,220
    Thanks. I always knew you were smarter than me.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Getting an error with OpenGL: collect2: ld returned 1 exit status
    By Lorgon Jortle in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2009, 09:18 PM
  2. Initializing a pointer in a class.
    By gpr1me in forum C++ Programming
    Replies: 3
    Last Post: 03-22-2006, 03:05 PM
  3. class passing a pointer to self to other class
    By daioyayubi in forum C++ Programming
    Replies: 3
    Last Post: 09-05-2005, 10:25 AM
  4. base class pointer problems
    By ... in forum C++ Programming
    Replies: 3
    Last Post: 11-16-2003, 11:27 PM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 07:49 PM

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