问题描述:

I am trying to create a derived class object in base class method.

I am getting the error as mentioned above. Below is a code snippet.

Any help?

 ---- Voip_connection.hh ----

#ifndef __VOIP_CONNECTION_HH

#define __VOIP_CONNECTION_HH

class VoipConnection {

public:

VoipConnection();

VoipConnection (ConnectionState* cs);

void update_last_data_rcvd_time() { last_data_rcvd_time_ = msec_time(); }

uint64_t last_data_rcvd_time() { return last_data_rcvd_time_; }

void set_voip_proto(int proto) { voip_proto_ = proto;}

~VoipConnection()

{

--nx_stat().act_connections;

voip_idle_wait_timer_clear();

sv_streaming_offset_ = 0;

cl_streaming_offset_ = 0;

}

// Lots and Lots of Other stuff

}

----Voip_sip.hh -----

#ifndef __VOIP_SIP_HH

#define __VOIP_SIP_HH

#include "voip_connection.hh"

class SipObj: public VoipConnection

{

/* stuff */

}

--- Voip_connection.cc ----

#include "voip_connection.hh"

class SipObj; // Tried this in .hh file as well.

VoipConnection::voip_process_pdu(bool from_client)

{

SipObj sip;

sip.process(datap, &pdu_len);

}

网友答案:

The second error points out that class VoipConnection has no default constructor which the constructor of SipObj tries to call.

The forward declaration of SipObj in Voip_connection.cc looks strange. Why does the implementation of a base class needs to know the existence of a derived class?

网友答案:

In order to instantiate a class, you need the complete type. This

SipObj sip;

requires the full definition of SipObj. A simple forward declaration won't do, you need to include the appropriate header.

In general, I would say that having a base class depend explicitly on one of it's derived types is a pretty bad idea.

Concerning the other error you report, it simply says that class VoipConnection has no default constructor. So you will have to provide one.

网友答案:

Okay this what I did. I needed the base class to instantiate the derived class.. I did the forward declaration in voip_sip.hh and included the voip_sip.hh file in voip_connection.hh

---- Voip_connection.hh ---- 

 #ifndef __VOIP_CONNECTION_HH
 #define __VOIP_CONNECTION_HH
 #include voip_sip.hh

class VoipConnection {

// Lots and Lots of Other stuff

}

----Voip_sip.hh -----

#ifndef __VOIP_SIP_HH
#define __VOIP_SIP_HH
class VoipConnection;

class SipObj: public VoipConnection 
{

/* stuff */
} 


--- Voip_connection.cc ----
#include "voip_connection.hh"
#include "voip_sip.hh"


VoipConnection::voip_process_pdu(bool from_client) 
{
 SipObj sip;
 sip.process(datap, &pdu_len);
 }
相关阅读:
Top