Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 552255
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T11:28:48+00:00 2026-05-13T11:28:48+00:00

I have a questing around such staff. There is a class A which has

  • 0

I have a questing around such staff.

There is a class A which has a object of type class B as it’s member. Since I’d like B to be a base class of group of other classes I need to use pointer or reference to the object, not it’s copy, to use virtual methods of B inside A properly. But when I write such code

class B
  {public:
     B(int _i = 1): i(_i) {};
     ~B() 
       {i = 0; // just to indicate existence of problem: here maybe something more dangerous, like delete [] operator, as well! 
        cout << "B destructed!\n";
       };
     virtual int GetI () const  {return i;}; // for example
   protected:
     int i;
  };

class A
  {public:
      A(const B& _b): b(_b) {}
      void ShowI () {cout <<b.GetI()<<'\n';};
   private:
      const B& b;
  }; 

and use it this way

B b(1);
A a(b);
a.ShowI();

it works perfectly:

1
B destructed!

But

A a(B(1));
a.ShowI();

give very unwanted result: object b creates and a.b is set as reference to it, but just after constructor of A finished, object b destructs! The output is:

B destructed!
0

I repeat again, that using copy of instead of reference to b in A

class A
  {public:
      A(B _b): b(_b) {}
      void ShowI () {cout <<b.GetI()<<'\n';};
   private:
      B b;
  }; 

won’t work if B is base class and A calls it’s virtual function. Maybe I’m too stupid since I do not know not know proper way to write necessary code to make it works perfectly (then I’m sorry!) or maybe it is not so easy at all 🙁

Of course, if B(1) was sent to function or method, not class constructor, it worked perfect. And of course, I may use the same code as in this problem as described here to create B as properly cloneable base or derived object, but doesn’t it appears too hard to for such easy looking problem? And what if I want to use class B that I could not edit?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T11:28:48+00:00Added an answer on May 13, 2026 at 11:28 am

    This is a standard issue, don’t fear.

    First, you could retain your design with a subtle change:

    class A
    {
    public:
      A(B& b): m_b(b) {}
    private:
      B& m_b;
    };
    

    By using a reference instead of a const reference, the compiler will reject the call to A’s constructor that is made with a temporary because it is illegal to take a reference from a temporary.

    There is no (direct) solution to actually retain the const, since unfortunately compilers accept the strange construct &B() even though it means taking the address of a temporary (and they don’t even shy to make it a pointer to non-const…).

    There are a number of so-called smart pointers. The basic one, in the STL is called std::auto_ptr. Another (well-known) one is the boost::shared_ptr.

    Those pointers are said to be smart because they allow you no to worry (too much) about the destruction of the object, and in fact guarantee you that it WILL be destroyed, and correctly at that. Thus you never have to worry about the call to delete.

    One caveat though: don’t use std::auto_ptr. It’s a mean beast because it has a unnatural behavior regarding copying.

    std::auto_ptr<A> a(new A());  // Building
    a->myMethod();                // Fine    
    
    std::auto_ptr<A> b = a;       // Constructing b from a
    b->myMethod();                // Fine
    a->myMethod();                // ERROR (and usually crash)
    

    The problem is that copying (using copy construction) or assigning (using assignment operator) means transfer of ownership from the copied toward the copying… VERY SURPRISING.

    If you have access to the upcoming standard, you can use std::unique_ptr, much like an auto pointer except from the bad behavior: it cannot be copied or assigned.

    In the mean time, you can simply use a boost::shared_ptr or perhaps std::tr1::shared_ptr. They are somewhat identical.

    They are a fine example of “reference counted” pointers. And they are smart at that.

    std::vector< boost::shared_ptr<A> > method()
    {
      boost::shared_ptr<A> a(new A());        // Create an `A` instance and a pointer to it
      std::vector< boost::shared_ptr<A> > v;
      v.push_back(a);                         // 2 references to the A instance
      v.push_back(a);                         // 3 references to the A instance
      return v;
    }                                         // a is destroyed, only 2 references now
    
    void function()
    {
      std::vector< boost::shared_ptr<A> > w = method(); // 2 instances
      w.erase(w.begin());                               // remove w[0], 1 instance
    }                                                   // w is destroyed, 0 instance
                                                        // upon dying, destroys A instance
    

    That’s what reference counted means: a copy and its original point to the same instance, and they share its ownership. And as long as there is one of them still alive, the instance of A exists, being destructed by the last one of them to die so you don’t have to worry about it!!

    You should remember though, that they do share the pointer. If you modify the object using one shared_ptr, all its relatives will actually see the change. You can do a copy in the usual mode with pointers:

    boost::shared_ptr<A> a(new A());
    boost::shared_ptr<A> b(new A(*a)); // copies *a into *b, b has its own instance
    

    So to sum up:

    • don’t use an auto_ptr, you’ll have bad surprises
    • use unique_ptr if available, it’s your safer bet and the easiest to deal with
    • use share_ptr otherwise, but beware of the shallow copy semantics

    Good luck!

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

No related questions found

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.