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 3344998
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T01:08:05+00:00 2026-05-18T01:08:05+00:00

I have a series of classes A , B , … which have many

  • 0

I have a series of classes A, B, … which have many derived classes which are created inside a module I do not wish to change.

Additionally, I have at least one class Z, which has to be informed whenever an object of type A (or derived classes) is created or destroyed. In the future, there may be more classes, Y, X that want to observe different objects.

I am looking for a convenient way to solve this.
At first glance, the problem seemed trivial, but I’m kind of stuck right now.

What I came up with, is two base classes SpawnObserver and SpawnObservable which are supposed to do the job, but I am very unhappy with them for several reasons (see attached simplification of these classes).

  1. When Z is notified, the actual object is either not yet or not anymore existent, due to the order in which base classes are created/destroyed. Although the pointers can be compared when destroying an object (to remove them from some data-structures in Z) this does not work when it is created and it surely does not work when you have multiple inheritance.
  2. If you want to observe only one class, say A, you are always notified of all (A, B, …).
  3. You have to explicitly if/else through all classes, so you have to know all classes that inherit from SpawnObservable, which is pretty bad.

Here are the classes, which I tried to trim down to the most basic functionality, which you need to know to understand my problem. In a nutshell: You simply inherit from SpawnObservable and the ctor/dtor does the job of notifying the observers (well, at least, this is what I want to have).

#include <list>
#include <iostream>

class SpawnObservable;

class SpawnObserver {
  public:
    virtual void ctord(SpawnObservable*) = 0;
    virtual void dtord(SpawnObservable*) = 0;
};

class SpawnObservable {
  public:
    static std::list<SpawnObserver*> obs;
    SpawnObservable() {
      for (std::list<SpawnObserver*>::iterator it = obs.begin(), end = obs.end(); it != end; ++it) {
        (*it)->ctord(this);
      }
    }
    ~SpawnObservable() {
      for (std::list<SpawnObserver*>::iterator it = obs.begin(), end = obs.end(); it != end; ++it) {
        (*it)->dtord(this);
      }
    }
    virtual void foo() {} // XXX: very nasty dummy virtual function
};
std::list<SpawnObserver*> SpawnObservable::obs;

struct Dummy {
  int i;
  Dummy() : i(13) {}
};

class A : public SpawnObservable {
  public:
    Dummy d;
    A() : SpawnObservable() {
      d.i = 23;
    }
    A(int i) : SpawnObservable() {
      d.i = i;
    }
};

class B : public SpawnObservable {
  public:
    B() { std::cout << "making B" << std::endl;}
    ~B() { std::cout << "killing B" << std::endl;}
};

class PrintSO : public SpawnObserver { // <-- Z
  void print(std::string prefix, SpawnObservable* so) {
    if (dynamic_cast<A*>(so)) {
      std::cout << prefix << so << " " << "A: " << (dynamic_cast<A*>(so))->d.i << std::endl;
    } else if (dynamic_cast<B*>(so)) {
      std::cout << prefix << so << " " << "B: " << std::endl;
    } else {
      std::cout << prefix << so << " " << "unknown" << std::endl;
    }
  }
  virtual void ctord(SpawnObservable* so) {
    print(std::string("[ctord] "),so);
  }
  virtual void dtord(SpawnObservable* so) {
    print(std::string("[dtord] "),so);
  }
};


int main(int argc, char** argv) {
  PrintSO pso;
  A::obs.push_back(&pso);
  B* pb;
  {
    std::cout << "entering scope 1" << std::endl;
    A a(33);
    A a2(34);
    B b;
    std::cout << "adresses: " << &a << ", " << &a2 << ", " << &b << std::endl;
    std::cout << "leaving scope 1" << std::endl;
  }
  {
    std::cout << "entering scope 1" << std::endl;
    A a;
    A a2(35);
    std::cout << "adresses: " << &a << ", " << &a2 << std::endl;
    std::cout << "leaving scope 1" << std::endl;
  }
  return 1;
}

The output is:

entering scope 1
[ctord] 0x7fff1113c640 unknown
[ctord] 0x7fff1113c650 unknown
[ctord] 0x7fff1113c660 unknown
making B
adresses: 0x7fff1113c640, 0x7fff1113c650, 0x7fff1113c660
leaving scope 1
killing B
[dtord] 0x7fff1113c660 unknown
[dtord] 0x7fff1113c650 unknown
[dtord] 0x7fff1113c640 unknown
entering scope 1
[ctord] 0x7fff1113c650 unknown
[ctord] 0x7fff1113c640 unknown
adresses: 0x7fff1113c650, 0x7fff1113c640
leaving scope 1
[dtord] 0x7fff1113c640 unknown
[dtord] 0x7fff1113c650 unknown

I want to stress, that I am perfectly aware why my solution behaves the way it does. My question is whether you have a better approach of doing this.

EDIT

As an extension to this question (and inspired by the comments below), I’d like to know:
Why do you think this is a terrible approach?

As an additional note: What I an trying to accomplish by this is to install a normal Observer in each and every created object.

EDIT 2

I will accept an answer that solves problem 1 (bold one in the enumeration above) or describes why the whole thing is a very bad idea.

  • 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-18T01:08:05+00:00Added an answer on May 18, 2026 at 1:08 am

    Use the curiously recurring template pattern.

    template<typename T> class watcher {
        typename std::list<T>::iterator it;
        watcher();
        ~watcher();
        void ctord(T*);
        void dtord(T*);    
    };
    template<typename T> class Observer {
    public:
    
        typedef std::list<T*> ptr_list;
        static ptr_list ptrlist;
        typedef typename ptr_list::iterator it_type;
        it_type it;
    
        typedef std::list<watcher<T>*> watcher_list;
        static watcher_list watcherlist;
        typedef typename watcher_list::iterator watcher_it_type;
    
        Observer() {
           ptrlist.push_back(this);
           it_type end = ptrlist.end();
           end--;
           it = end;
           for(watcher_it_type w_it = watcherlist.begin(); w_it != watcherlist.end(); w_it++)
               w_it->ctord(this);
        }
        ~Observer() {
            ptrlist.erase(it);
           for(watcher_it_type w_it = watcherlist.begin(); w_it != watcherlist.end(); w_it++)
               w_it->ctord(this);
        }
    };
    class A : public Observer<A> {
    };
    class B : public Observer<B> {
    };
    class C : public A, public B, public Observer<C> {
        // No virtual inheritance required - all the Observers are a different type.
    };
    template<typename T> watcher<T>::watcher<T>() {
        Observer<T>::watcherlist.push_back(this);
        it = watcherlist.end();
        it--;         
    }
    template<typename T> watcher<T>::~watcher<T>() {
        Observer<T>::watcherlist.erase(it);
    }
    template<typename T> void watcher<T>::ctord(T* ptr) {
        // ptr points to an instance of T that just got constructed
    }
    template<typename T> void watcher<T>::dtord(T* ptr) {
        // ptr points to an instance of T that is just about to get destructed.
    }
    

    Not just that, but you can inherit from Observer multiple times using this technique, as two Observer<X> and Observer<Y> are different types and thus doesn’t require diamond inheritance or anything like that. Plus, if you need different functionality for Observer<X> and Observer<Y>, you can specialize.

    Edit @ Comments:

    class C DOES inherit from Observer<A> and Observer<B> through A and B, respectively. It doesn’t need to know or care whether or not they’re being observed. A C instance will end up on all three lists.

    As for ctord and dtord, I don’t actually see what function they perform. You can obtain a list of any specific type using Observer::ptrlist.

    Edit again: Oooooh, I see. Excuse me a moment while I edit some more. Man, this is some of the most hideous code I’ve ever written. You should seriously consider not needing it. Why not just have the objects that need to be informed about the others do their creation?

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

Sidebar

Related Questions

I have a series of Python classes in a file. Some classes reference others.
I have a series of classes representing smart map elements: MapTextElement , MapIconElement ,
I have a series of extension methods defined for various classes in a C#
I have a constructor that has a series of classes and functions within it
So here is the scenario: i have a series of different repository classes that
I have a series of policy objects which I thought would be convenient to
I have a series of image thumbnails in a page. They are created using
A quick question. I have a series of DIVs with the following classes .level1
I am building a page through a series of include files. Many (not all)
I have a series of PDFs named sequentially like so: 01_foo.pdf 02_bar.pdf 03_baz.pdf etc.

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.