can I declare a class variable inside that class method?

Discussion in 'C++' started by John Black, Jun 15, 2004.

  1. John Black

    John Black Guest

    Hi,
    Suppose I have a class,

    class MyClass{
    public:
    MyClass();
    MyClass(MyClass);

    int func();
    };

    Then can I declare a MyClass object inside MyClass::func()?

    int MyClass::func(){
    MyClass obj;
    <......>
    }
     
    John Black, Jun 15, 2004
    #1
    1. Advertising

  2. John Black wrote:
    >
    > Suppose I have a class,
    >
    > class MyClass{
    > public:
    > MyClass();
    > MyClass(MyClass);


    Suppose you wrote

    MyClass x;
    MyClass y(x);

    Because the copy constructor parameter is passed by value, a copy of x
    is made, and the copy is sent to the copy constructor. But to make the
    copy, the MyClass copy constructor would have to be invoked. And then
    the argument would have to be copied, using the MyClass copy constructor
    again. And so on...

    The point is, your copy constructor should take a reference, not a copy:

    MyClass(MyClass const &);

    > int func();
    > };
    >
    > Then can I declare a MyClass object inside MyClass::func()?
    >
    > int MyClass::func(){
    > MyClass obj;
    > <......>
    > }


    Sure.

    --
    Russell Hanneken

    Use ROT13 to decode my email address.
     
    Russell Hanneken, Jun 15, 2004
    #2
    1. Advertising

  3. John Black

    jeffc Guest

    "John Black" <> wrote in message
    news:...
    > Hi,
    > Suppose I have a class,
    >
    > class MyClass{
    > public:
    > MyClass();
    > MyClass(MyClass);
    >
    > int func();
    > };
    >
    > Then can I declare a MyClass object inside MyClass::func()?
    >
    > int MyClass::func(){
    > MyClass obj;
    > <......>
    > }
    >


    Yes. Just don't do this :)
    int MyClass::func()
    {
    MyClass obj;
    obj.func();
    }
     
    jeffc, Jun 15, 2004
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Angus Parvis
    Replies:
    14
    Views:
    812
  2. CJ
    Replies:
    6
    Views:
    475
  3. johnmmcparland
    Replies:
    3
    Views:
    545
    Gavin Deane
    Mar 29, 2007
  4. ZelluX
    Replies:
    24
    Views:
    914
    Hendrik Maryns
    Nov 19, 2007
  5. Juha Nieminen
    Replies:
    3
    Views:
    1,177
    Juha Nieminen
    Feb 22, 2008
Loading...

Share This Page