PDA

View Full Version : doubt in parent and child class



iswaryasenthilkumar
26th November 2015, 08:47
need to call parent method or variable in child class.
i created parent class (QWidget)
Widget.h


#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include<QtGui>
#include"secdialog.h" //child class
namespace Ui {
class Widget;
}

class Widget : public QWidget
{
Q_OBJECT

public:
QPushButton *button1;
QString list;
private:
Ui::Widget *ui;
secDialog *sec; //creating object to child class
public slots:
void display();
}

secDialog.h
child class (QDialog


#ifndef SECDIALOG_H
#define SECDIALOG_H
#include <QDialog>
#include<QWidget>
#include<QtGui>
#include"widget.h"//parent class
namespace Ui {
class secDialog;
}

class secDialog : public QDialog
{
Q_OBJECT

public:
Private :
Widget *widget;//create object for parent class
public slots:
void newmethod();
}

Widget.cpp


#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
button1=new QPushButton("CLICK",this);
button1->show();
connect(button1,SIGNAL(clicked()),this,SLOT(displa y());
ui->setupUi(this);
}
void Widget::display()
{
sec=new secDialog(this);
sec->show();
}

secDialog.cpp


#include "secdialog.h"
#include "ui_secdialog.h"
secDialog::secDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::secDialog)
{
newmethod();
}
void secDialog::newmethod()
{
widget=new QWidget(this);
widget->list="Hello";
qDebug<<widget->list;
}

When i execute this ,i getting Error,

"widget does not name a type"
i need to use both class variables and button,i know somewhere am doing wrong can any one help to solve this problem,:(
Thanks in advance:o

anda_skoa
26th November 2015, 09:12
You have recursive includes, better use forward declarations in the headers to make each other type known and only include the other class' header in the source

widget.h


class secDialog; // instead of #include "secDialog.h"


widget.cpp


#include"secDialog.h" // include moved to the cpp file


secDialog.h


class Widget; // instead of #include "widget.h"


secDialog.cpp


#include"widget.h" // include moved to the cpp file


Cheers,
_

iswaryasenthilkumar
26th November 2015, 10:38
Thanks it works anda_skoa

You have recursive includes, better use forward declarations in the headers to make each other type known and only include the other class' header in the source

widget.h


class secDialog; // instead of #include "secDialog.h"


widget.cpp


#include"secDialog.h" // include moved to the cpp file


secDialog.h


class Widget; // instead of #include "widget.h"


secDialog.cpp


#include"widget.h" // include moved to the cpp file


Cheers,
_