Skip to content

Instantly share code, notes, and snippets.

@j2doll
Last active August 22, 2019 12:02
Show Gist options
  • Save j2doll/e630594defacc8b58fe642b2135573fe to your computer and use it in GitHub Desktop.
Save j2doll/e630594defacc8b58fe642b2135573fe to your computer and use it in GitHub Desktop.
Qt Polymorphism

Qt Polymorphism

a

  • a.h
#ifndef A_H
#define A_H
#include <QtGlobal>
#include <QObject>

class A : public QObject
{
   Q_OBJECT
  public:
  A(QObject* parent = NULL);
};

#endif // A_H
  • a.cpp
#include "a.h"

A::A(QObject* parent)
 : QObject(parent)
{
}

b

  • b.h
#ifndef B_H
#define B_H
#include <QtGlobal>
#include <QObject>
#include "A.h"

class B : public A
{
  Q_OBJECT
 public:
  B(QObject* parent = NULL);
};

#endif // B_H
  • b.cpp
#include "b.h"

B::B(QObject* parent)
 : A(parent)
{
}

main

  • main.cpp
#include <cstdio>
#include <string>
#include <QtCore/QCoreApplication>
#include <QDebug>
#include "a.h"
#include "b.h"

int main(int argc, char *argv[])
{
  QCoreApplication a(argc, argv);

  QObject *obj = new B; // polymorphism in object-oriented programming
  qDebug() << QString( obj->metaObject()->className() ); // print "B"
  
  return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment