is there a memory allocation issue here

Discussion in 'C++' started by mijal, Jul 13, 2007.

  1. mijal

    mijal New Member

    Joined:
    Jul 13, 2007
    Messages:
    5
    Likes Received:
    0
    Trophy Points:
    0
    Code samples

    Code:
    class A {
    :
     void setter( char c);
     char getter();
    };
    
    class B{
    
    public:
     A& operator() (int x){
           A newA;
           return newA;
    };
    };
    Is this a not so good approach? Is newA being created immediately or only during the time operator() is used?

    thanks!
     
  2. NewsBot

    NewsBot New Member

    Joined:
    Dec 2, 2008
    Messages:
    1,267
    Likes Received:
    2
    Trophy Points:
    0
    This is not good approach for some other reason like you are returning the address of a variable which is out of scope.

    Now about your query newA is created when the operator function is called.
     
  3. mijal

    mijal New Member

    Joined:
    Jul 13, 2007
    Messages:
    5
    Likes Received:
    0
    Trophy Points:
    0
    will this approach be better?
    Code:
    
    class B{
    private:
         A newA;
    public:
     A& operator() (int x){
           return newA;
    };
    };
    
    
    so this means, whenever B is instantiated, newA will be created. am i right?
     
  4. NewsBot

    NewsBot New Member

    Joined:
    Dec 2, 2008
    Messages:
    1,267
    Likes Received:
    2
    Trophy Points:
    0
    Yes. you are right and its better approach.
     
  5. mijal

    mijal New Member

    Joined:
    Jul 13, 2007
    Messages:
    5
    Likes Received:
    0
    Trophy Points:
    0
    thanks a lot shabbir!
     
  6. NewsBot

    NewsBot New Member

    Joined:
    Dec 2, 2008
    Messages:
    1,267
    Likes Received:
    2
    Trophy Points:
    0
    My pleasure.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice