Superclasses and subclasses

Hi guys,
I want to make a subclass of Avogadro::Molecule. Can I do that kind of association?

superclass: Molecule
subclass: CustomMolecule

Molecule *parent = gl->molecule();
CustomMolecule *child = parent;

(gl is the GLWidget). I know this seems to be an easy question, but I face some problems and I am not so familiar with C++… Thanks,

Marc

On Fri, Jun 14, 2013 at 7:16 AM, Marc-André Dubois ma.dubois@me.com wrote:

Hi guys,
I want to make a subclass of Avogadro::Molecule. Can I do that
kind of association?

superclass: Molecule
subclass: CustomMolecule

It is possible to subclass Molecule. The XtalOpt extension does this a lot, e.g.

https://github.com/dlonie/XtalOpt/blob/stable/src/globalsearch/structure.h

Molecule *parent = gl->molecule();
CustomMolecule *child = parent;

This wouldn’t work – you can’t expect the gl->molecule() to be the
CustomMolecule type. In C++, the object’s type is fixed when it is
instantiated – an object instantiated as a Molecule cannot be used as
a CustomMolecule. However, if the “parent” pointer above is actually
pointing to an instance of CustomMolecule, you can safely recover the
CustomMolecule pointer with:

Molecule *mol = gl->molecule();
CustomMolecule customMol = dynamic_cast<CustomMolecule>(mol);
if (customMol != 0) {
… // do work with customMol pointer.
}

The dynamic_cast will check if the object pointed to by “mol” is
actually an instance of CustomMolecule. If it is, it returns a
CustomMolecule* pointer to the object. If it is not, if returns 0.
This is how to check if a pointer can be safely downcast into a
subclass type.

HTH,
Dave

(gl is the GLWidget). I know this seems to be an easy question, but I face
some problems and I am not so familiar with C++… Thanks,

Marc


This SF.net email is sponsored by Windows:

Build for Windows Store.

http://p.sf.net/sfu/windows-dev2dev


Avogadro-devel mailing list
Avogadro-devel@lists.sourceforge.net
avogadro-devel List Signup and Options