c++qtpointersqtcpsocket

How can a pointer data type variable can contain an object?


I'm rather new to c++ / QT and i'm having hard time to understand a bunch of code from a TCP Socket tutorial (https://www.bogotobogo.com/Qt/Qt5_QTcpSocket_Signals_Slots.php).

This is the mytcpsocket.h file (class declaration) :

#ifndef MYTCPSOCKET_H
#define MYTCPSOCKET_H

#include <QObject>
#include <QTcpSocket>
#include <QAbstractSocket>
#include <QDebug>

class MyTcpSocket : public QObject
{
    Q_OBJECT
public:
    explicit MyTcpSocket(QObject *parent = 0);

    void doConnect();

signals:

public slots:
    void connected();
    void disconnected();
    void bytesWritten(qint64 bytes);
    void readyRead();

private:
    QTcpSocket *socket;

};

#endif // MYTCPSOCKET_H

So, there is a private attribute called "socket" which is pointer type in the class declaration.

This is the mytcpsocket.cpp file (class definition) :

// mytcpsocket.cpp

#include "mytcpsocket.h"

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

void MyTcpSocket::doConnect()
{
    socket = new QTcpSocket(this);

    connect(socket, SIGNAL(connected()),this, SLOT(connected()));
    connect(socket, SIGNAL(disconnected()),this, SLOT(disconnected()));
    connect(socket, SIGNAL(bytesWritten(qint64)),this, SLOT(bytesWritten(qint64)));
    connect(socket, SIGNAL(readyRead()),this, SLOT(readyRead()));

    qDebug() << "connecting...";

    // this is not blocking call
    socket->connectToHost("google.com", 80);

    // we need to wait...
    if(!socket->waitForConnected(5000))
    {
        qDebug() << "Error: " << socket->errorString();
    }
}

You can see in the doConnect() method that it's initializing that "socket" attribute (which is a pointer, right?) with an object from the class QTcpSocket.

How is it possible ? I mean, from what i've learned ;

int number{10};
int *ptr_number = &number
ptr_number // variable that store number's memory address.
*ptr_number = number // deferencing ptr_pointer.

So it should be :

*socket = new QTcpsocket(this);

Instead of :

socket = new QTcpsocket(this); 

Here, "socket" should just contains a memory address, no ? How can we affect something to it ?

Plus, another small question ; Why are we not using "this" keyword to initialize attributes in the class declaration ? :

this->socket = new QTcpsocket(this);

I apology if these questions might look a bit silly, but i can't find any good explanations around... Thanks in advance!


Solution

  • The operator new returns a pointer to the newly allocated memory.

    Regarding this->socket, it's implicitly assumed and we can directly use socket variable.

    Thank you @CinCout and @vahancho !