Re: Passing an object pointer to function
- From: "Tom Serface" <tserface@xxxxxxx>
- Date: Tue, 16 Aug 2005 12:45:27 -0700
Just past the pointer created in the new call pRags without the '&'.
Remember to delete the object when you are done with it because it won't
delete automatically.
Tom
"Robby" <Robby@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote in message
news:F1E47B10-0892-4320-9AB7-2B983AE088BA@xxxxxxxxxxxxxxxx
> Hi,
> Below I am passing an object to a function by reference. Please consider
> the
> following code fragment:
>
> #include <iostream>
> using namespace std;
>
> class SimpleCat
> {
> public:
> SimpleCat();
> ~SimpleCat();
> int GetAge() {return itsAge;}
> void SetAge(int age) {itsAge = age;}
>
> private:
> int itsAge;
> };
>
> SimpleCat::SimpleCat()
> { cout << "Constructor called. \n";
> itsAge = 1; }
>
> SimpleCat::~SimpleCat()
> { cout << "Destructor called \n"; }
>
> void Function1(SimpleCat *pRags);
>
> int main()
> {
> int a;
> SimpleCat Frisky;
> Function1(&Frisky);
> cout << Frisky.GetAge();
> }
>
> void Function1(SimpleCat *pRags)
> { pRags->SetAge(50); }
>
> The above code works fine, however what if in main I wanted to create a
> pointer to an object on the heap using the following line:
>
> SimpleCat * pRags = new SimpleCat;
>
> and then passing only the pointer of the object to my function: Please
> consider the following code which does not complile?
>
> #include <iostream>
> using namespace std;
>
> class SimpleCat
> {
> public:
> SimpleCat();
> ~SimpleCat();
> int GetAge() {return itsAge;}
> void SetAge(int age) {itsAge = age;}
>
> private:
> int itsAge;
> };
>
> SimpleCat::SimpleCat()
> {
> cout << "Constructor called. \n";
> itsAge = 1;
> }
>
> SimpleCat::~SimpleCat()
> {
> cout << "Destructor called \n";
> }
>
> void Function1(int *pRags);
>
> int main()
> {
> int a;
> SimpleCat * pRags = new SimpleCat;
> Function1(&pRags);
> cout << Frisky.GetAge();
> }
>
> void Function1(int *pRags)
> {
> pRags->SetAge(50);
> }
>
> I don't know if this is possible to do in VC++. And since I am passing a
> pointer to an object on the heap, is my function prototype an header
> correct?
>
> void Function1(int *pRags)
>
> I am sorry if this is a stupid question but the book examples somehow
> don't
> go into this probability, so I am just being curious!
>
> Anyone, all help greatly appreciated!
>
> --
> Best regards
> Robert
.
- References:
- Passing an object pointer to function
- From: Robby
- Passing an object pointer to function
- Prev by Date: Re: Passing an object pointer to function
- Next by Date: Re: How to get Computer Name given IP address?
- Previous by thread: Re: Passing an object pointer to function
- Index(es):
Relevant Pages
|