-1

I am not really good in c++ so I really need your help. I am using a method inside an object and I would like to access other object members. How can I do that in a better way and not violating OOP?

This is my .h

class XSection
{
private:    
    char *m_sname;
    XSection *m_snext;
};

class XIniFile
{

private:
    char *m_iname;
    XSection *m_isections;

XSection *addSection(const char *);
}

and I have something like this in .cpp

XSection *XIniFile::addSection(const char *d)
{
    XSection *sn = (XSection *) malloc (sizeof(XSection *));    

    sn->m_sname = strdup(d); 
    return sn;
}

I am having an error of char* XSection::m_sname is private char *m_name;

How could I use it?

Gibs
  • 774
  • 9
  • 26
  • 3
    In order from worst to best: make the member `public`, make the class a `friend` of `XIniFile`, write a setter method, write a constructor. Also, use `new` instead of `malloc`, or better still just return an actual object, not a pointer. – user657267 Jul 30 '14 at 02:16
  • http://stackoverflow.com/questions/184537/in-what-cases-do-i-use-malloc-vs-new/184540#184540 – drescherjm Jul 30 '14 at 02:23
  • 2
    Replace the whole thing by `std::list` – M.M Jul 30 '14 at 02:25

1 Answers1

2

In general, this is considered bad practice because it violates the concept of encapsulation. In this case, it would be best to give XSection a constructor that sets it up with the desired parameters, and use new instead of malloc. For example:

The constructor definition:

XSection(char* name);

Implementation:

XSection(char* name) : m_iname(name) { }

Usage:

XSection* sn = new XSection(strdup(d));

But to answer the question directly: if you must, you could make XIniFile a friend class of XSection:

class XSection
{
    friend class XIniFile;
MrEricSir
  • 8,044
  • 4
  • 30
  • 35
  • Thank you MrEricSir! I am actually migrating a c program to c++ oop. ---- I really hate it when someone reps me down because of a noob question. I was just asking how I could improve the program. – Gibs Jul 30 '14 at 06:07