Javier Ramírez
Javier Ramírez

Reputation: 1011

Friend function in class

Can any one help me please?. I have my files:

prueba.h

#ifndef PRUEBA_H
#define PRUEBA_H

#include <iostream>
#include <cstring>

using namespace std;

class cadena{
  public:
   cadena();
   cadena(const char *c);
   cadena(int n);
   cadena(const cadena &Cad);
   ~cadena();
   void DevDir();
   void Asignar(const char *dest);
   char *Leer(char *c);
  private:
    char *cad;
    short valor;
    friend void tec(cadena obj);
};

#endif

prueba.cpp

#include "prueba.h"

cadena::cadena():cad(NULL),valor(128){}

cadena::cadena(const char *c){
  cad = new char[strlen(c)+1];
  strcpy(cad,c);
}

cadena::cadena(int n){
  cad = new char[n+1];
  cad[0] = 0;
}

cadena::cadena(const cadena &Cad){
  cad = new char[strlen(Cad.cad)+1];
  strcpy(cad,Cad.cad);
}

cadena::~cadena(){
  delete[] cad;
}

void cadena::DevDir(){
  cout << "dir valor: " << &cad << endl;
}

void cadena::Asignar(const char *dest){
  delete[] cad;
  cad = new char[strlen(dest)+1];
  strcpy(cad,dest);
}

char *cadena::Leer(char *c){
  strcpy(c,cad);
  return c;
}

void tec(cadena obj){
  cout << obj.valor << endl;
}

and my file main:

#include "prueba.h"

int main(){
    cadena Cadena1;

    tec(Cadena1);

    cin.get();
    return 0;
}

The problem is my friend function (tec). No problem to compile, but when run it shows me an error as when a memory access violation.

If I remove this function of main, everything works fine.

I use Code::blocks and using debbuger mode show me this:

  1. That the error is in main, in tec function.
  2. That the error is in .cpp file, in constructor copy definition.

But if I remove tec function of main, I get no errors.

Upvotes: 0

Views: 110

Answers (1)

ruakh
ruakh

Reputation: 183602

Your immediate problem is that your default constructor initializes cad to NULL:

cadena::cadena():cad(NULL),valor(128){}

but your copy-constructor passes its argument's cad to strlen:

cadena::cadena(const cadena &Cad){
  cad = new char[strlen(Cad.cad)+1];
  strcpy(cad,Cad.cad);
}

which is illegal when it's NULL.

The simplest fix, in this case, is probably to check for NULL explicitly:

cadena::cadena(const cadena &Cad){
  if(Cad.cad == NULL) {
    cad = NULL;
  } else {
    cad = new char[strlen(Cad.cad)+1];
    strcpy(cad,Cad.cad);
  }
}

but it would be much better to use std::string instead of explicitly managing this memory. That would eliminate this problem and several others.

Upvotes: 2

Related Questions