Access to parent class instance

Hello,

What is the best way to access an instance of a parent class from a child class.
Do you use singleton, virtual inheritance or something else?


Thanks!
This is way to broad too answer, what are you trying to do?

If I were to take your question literally, I would post something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Base
{
};

class Child : public Base
{
  void something( const Base& )
  {
    // access achieved
  }
};

int main( void )
{
  Base base;
  Child child;

  child.something( base );
}


If I were to take a guess at what you want, I would say that you want to call a function of a base class that has been overridden by the child. In this case:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>

class Base
{
  public:
  virtual ~Base( void ){}

  virtual void something( void ) const { std::cout << "Hello from Base\n"; }
};

class Child : public Base
{
  public:
  virtual ~Child( void ){}

  void something( void ) const override
  {
    Base::something();
    std::cout << "Hello from child\n";
  }
};

int main( void )
{
  Child().something();
}
Hello,

Thank you for your reply.
In more detail, I have a mainwindow class for all the UI.
When I click on a button it creates a new dialog which says what type of document you want.
1
2
3
4
5
void MainWindow::on_actionFileNew_triggered()
{
    NewDocumentSelector newdocumentselector;
    newdocumentselector.exec();
}


When I select an option in NewDocumentSelector dialog, I want to tell MainWindow about this.
I am using Qt library so I could connect the events together but I think MainWindow class will become messy.
I am looking for a way for NewDocumentSelector to be used in MainWindow and other classes for example:

1)
MainWindow.cpp
1
2
3
4
...
NewDocumentSelector newdocumentselector(this);
newdocumentselector.exec();
..


Now I can call MainWindow instance method such as
MainWindow->notepadDocumentSelected();
from inside NewDocumentSelector


or

2)
Singleton pattern

or

3)
Virtual Base Classes
http://pic.dhe.ibm.com/infocenter/ratdevz/v8r5/index.jsp?topic=%2Fcom.ibm.tpf.toolkit.compilers.doc%2Fref%2Flangref_os390%2Fcbclr21020.htm

Which or another is the best choice?

Thanks
Last edited on
I would say virtual base classes is out, a NewDocumentSelector is not a MainWindow.

I don't think it is an appropriate use of a Singleton pattern, it seems like it is just an excuse to have a global variable.

The first way seems like the best bet, I don't know how to use Qt, but this does look like the way it was intended to be used. If you want to trim down the code in your MainWindow, my first idea would be to create a class derived from whatever you are using to create the action for the dialogue being opened in the first place.
Topic archived. No new replies allowed.