0

I'm trying to declare pointer to class at one function, and call another function with this pointer as parameter. Another function trying to create class and assign pointer to this new created class to input pointer.

First method:

size_t packetLen = 0;
ETH2::PacketEthernetII* eth = NULL; 
IPv4::PacketIPv4* ip4 = NULL;   
ICMP::PacketICMP* icmp = NULL;
TCP::PacketTCP* tcp = NULL;
UDP::PacketUDP* udp = NULL;
if (!buildPackets(formats, packetLen, eth, ip4, icmp, tcp, udp)) {}

Another method:

    bool Device::buildPackets(const Tokens& formats, size_t& packetLen, 
        ETH2::PacketEthernetII* eth, IPv4::PacketIPv4* ip4, 
        ICMP::PacketICMP* icmp, TCP::PacketTCP* tcp, UDP::PacketUDP* udp)
    {
        for (size_t i = 0; i < formats.size(); ++i) {       
                if (Utilities::startsWith(formats[i], ETH2PROTO)) {             
                    eth = createEthernet2(formats[i]);          
                    if (!eth) 
                        return false;           
                    packetLen += eth->len();            
                }
        }   
        return true;
}

Second method is working and eth takes value to the object. But after return to first method, eth is null... And I don't know why. What important detail about pointers I missed?

3ka5_cat
  • 121
  • 1
  • 12
  • 1
    Pass the pointers by reference, e.g. `ETH2::PacketEthernetII*& eth` instead of `ETH2::PacketEthernetII* eth`. – ildjarn Nov 08 '12 at 21:14
  • It works, thx. But why it must be passed by reference? – 3ka5_cat Nov 08 '12 at 21:17
  • Because C++ passes arguments by value. This means every function call copies all its parameters so that changes in value don't propagate outside the function. Passing by reference changes this behavior to not copy the parameter, making changes visible outside the function. – stonemetal Nov 08 '12 at 21:22
  • @3ka5_cat: Otherwise you get a *copy* of the parameter value, which is a pointer. – Ben Voigt Nov 08 '12 at 21:22
  • Pointer to pointer would also work, though I would prefer a reference. – Ed S. Nov 08 '12 at 21:22
  • @3ka5_cat : Well, read up on references and see what their characteristics are. ;-] Maybe [a good book](http://stackoverflow.com/q/388242/636019) will help... – ildjarn Nov 08 '12 at 21:22
  • thx to all. Read about this few weeks ago, and forgot > – 3ka5_cat Nov 08 '12 at 21:26

1 Answers1

1

Call by reference:

bool Device::buildPackets(const Tokens& formats, size_t& packetLen, 
    ETH2::PacketEthernetII* &eth, IPv4::PacketIPv4* ip4, 
    ICMP::PacketICMP* icmp, TCP::PacketTCP* tcp, UDP::PacketUDP* udp)
Roozbeh Zabihollahi
  • 7,207
  • 45
  • 39