Defining two classes inside a class, and accessing its members - c++

I'm trying to access members of a classC from classB, both classC and classB are inside classA. Here is what I'm trying to do;
//hello.h
class hello{
public:
hello();
class letters{
public:
letters();
void setName(char n);
char getName();
private:
char name;
}
class sayHi{
public:
sayHi();
void onJoin();
}
}
//hello.cpp
hello::hello(){}
hello::letters(){}
hello::sayHi(){}
void hello::letters::setName(char n){
hello::letters::name = n; //trying to access the private variable 'name' inside class letters
}
char hello::letters::getName(){
return hello::letters::name = n;
}
void hello::sayHi::onJoin(){
cout<< hello::letters::getName() <<endl;
}
I know i'm doing it wrong, am I supposed to create instances of each class and call the members?

Yes, you're supposed to create instances of the classes.
These are frequently called "objects", which is why they call it "object-oriented programming".
First, your getName and setName should look like this:
void hello::letters::setName(char n) {
name = n;
}
char hello::letters::getName() const { // Declaration should also say "const".
return name;
}
With that out of the way, any sayHi instance needs to know which letters to say "Hi" to, which means that you need to tell it.
This is usually done by passing a parameter to the method that needs to know:
class sayHi{
public:
sayHi();
void onJoin(const letters& who)
{
cout << who.getName() << endl;
}
};
which you would use somewhat like this:
int main()
{
hello::letters letter;
letter.setName('p');
hello::sayHi greeter;
greeter.onJoin(letter);
}

What is the error you are getting ? where have you created objects for accessing these methods ? Also
return hello::letters::name = n;
this line is wrong, it should be
return hello::letters::name;

Related

Access function from another class without having any relations

I'm still new to C++ and I'm trying to know if it is possible to access a function from another class knowing that no one is the father class here . This is a piece of my program to show you what I want to do exactly .
class CSubject
{
public:
CSubject() = default;
CSubject(std::string m_Name){this->Name = m_Name;}
void print(){ std::cout << Name;}
~CSubject(){}
private:
std::string Name;
};
class CStudent
{
public:
CStudent() = default;
void Method2()
{
//Call the print method and print the name "test"
}
~CStudent(){}
private:
};
int main()
{
CSubject AE("test");
CStudent ST;
ST.Method2(); //Print test;
return 0;
}
Forget about classes for a second. You want to call Method2(), and from there, print information that was put into the AE. Suppose you didn't have two classes of your own, but rather, say:
void Method2();
int main() {
const char* AE = "Test";
// ...
Method2();
}
That wouldn't work, right? And it shouldn't work, because local variables in a function (like main()) are usable only within that function's body; that's their local scope. For Method2() to use AE in any way, you have to let Method2() "know" about it. It's the same with classes.
You could use static method and attributes, which can be altered by creating an instance and overwriting it and also getting them from unrelated processes.
I would edit your CSubject class like this:
class CSubject {
public:
CSubject() = default;
CSubject(std::string m_Name) {
CSubject::Name = m_Name;
}
static void print() {
if (CSubject::Name.empty()) //checking is a good practice
std::cout << "The name is empty...\n";
else
std::cout << Name;
}
~CSubject() {}
private:
static std::string Name;
};
And you could access the print method from your Method2 like this:
void Method2() {
CSubject::print();
}
But beware! The static attribute is the only one for the class. If you plan on creating multiple CSubject instances and their new names, then you could store the m_Name attribute as non-static private, print() as non-static public, and Method2 should have a parameter where you pass the CSubject (the whole object or just the data that you need) that is in your interest.

Efficiently manage same code for single element or array of elements

I have a large class with many methods. This class has a subclass that manages a different situation.
Just to clear it up with an example the actual situation is the following:
class Logic {
public:
virtual void method()
{
Something::getInstance()->doSomething();
}
};
class ArrayLogic : public Logic {
private:
Something** array;
public:
void method() override
{
for (int i = 0; i < AMOUNT; ++i)
array[i]->doSomething();
}
};
Now this pattern repeats itself in multiple methods and I'd like to have just one implementation without trading for performance (since some of this methods are actually already proven to require efficiency).
I was thinking if it's possible with C++11 to have a template solution approach which is able to manage this situation at compile time without the necessity to duplicate the code.
Mind that the array doesn't make sense to exist for Logic so having a Something*[1] is not a viable option.
An additional problem is that at the moment Something** array is not directly contained in ArrayLogic but resides in another class, so it's more like
class ArrayLogic : public Logic {
private:
Container* container;
public:
void method() override {
for (int i = 0; i < AMOUNT; ++i)
if (container->array[i])
container->array[i]->doSomething();
}
}
While having to check for container->array[i] != nullptr may seems strange the fact is that the position is relevant, so an element removed from the array doesn't cause a shift of the successive element but leaves a hole.
I'd try and create separate classes for single and multiplayer games. Base both of these on a base class LogicBase that has a method(Something*) function that calls doSomething() on its parameter. This is what #Pradhan was referring to.
In your main game, you can use a LogicBase* to refer to either a SinglePlayerLogic or a MultiPlayerLogic object and call the relevant method() using a virtual function call.
I'm passing what is stored in Container to the constructor of MultiPlayerLogic. But it could be in a separate class and accessed that way. Similarly, it may be cleaner to pass a Something to the constructor of SinglePlayerLogic, but I wanted to keep the code structure close to your original, so didn't do this.
It initially looks funny for LogicBase to call to a subclass, then have those subclasses call the protected method(Something*) back in the super class. I've seen it elsewhere as a design pattern, but can't recall it's name.
#include <iostream>
#include <vector>
const int AMOUNT = 5;
struct Something {
void doSomething() { std::cout << "Something::doSomething\n"; }
static Something* getInstance() { static Something s; return &s; }
};
class LogicBase {
public:
virtual void method() = 0;
protected:
void method(Something* s) { s->doSomething(); }
};
class SinglePlayerLogic : public LogicBase {
public:
void method() override
{
std::cout << "SinglePlayer::method\n";
LogicBase::method(Something::getInstance());
}
};
class MultiPlayerLogic : public LogicBase {
public:
MultiPlayerLogic(Something **s) : players(s) {}
void method() override
{
std::cout << "MultiPlayer::method\n";
for (int i = 0; i < AMOUNT; ++i) {
if (players[i] == nullptr) {
continue;
}
std::cout << i << " ";
LogicBase::method(players[i]);
}
}
private:
Something** players;
};
int main() {
LogicBase* lb;
SinglePlayerLogic spl;
lb = &spl;
lb->method();
std::vector<Something*> players{AMOUNT};
MultiPlayerLogic mpl(players.data());
lb = &mpl;
lb->method();
}

A private variable can be accessed from another object of the same type? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
With a private modifier, why can the member in other objects be accessed directly?
Private members of a C++ class are designed to be invisible to other class instances. I'm confused since private members can be accessed as shown below! Can anyone explain it to me?
Here's my code:
#include <iostream>
using namespace std;
class Person
{
private:
char* name;
int age;
public:
Person(char* nameTemp, int ageTemp)
{
name = new char[strlen(nameTemp) + 1];
strcpy(name, nameTemp);
age = ageTemp;
}
~Person()
{
if(name != NULL)
delete[] name;
name = NULL;
}
bool Compare(Person& p)
{
//p can access the private param: p
//this is where confused me
if(this->age < p.age) return false;
return true;
}
};
int main()
{
Person p("Hello, world!", 23);
return 0;
}
Methods of a class can access its private attributes throughout all class instances, at least in C++.
Any snippet of code that "belongs" to the type Person will be able to access public, protected and private variables of any Person object.
The type matters here, not the instance.
When a variable is designated private, it means that only methods of this class and optionally classes and methods designated as friends can access it. Any instance of the class can access private variables of all other instances of the same class.
if(this->age < p.age) return false;
p.age: age is private, and can access like this because this line is inside the method of class, so it can access all private member.
if you put p.age outside method of class, it will notice error. For example:
int main()
{
Person p("Hello, world!", 23);
// will be error, because main is not inside class People
if (p.age < 18) {
cout << "You are not adult" << endl;
}
return 0;
}
Hope this help :)
Any access outside of the class is "prohibited". Unless you for example use the friend class. (Which let's any other class access to the private members of the class)
You can define friend-class like this:
class MyClass {
friend class MyClassB;
public:
MyClass();
~MyClass();
private:
int number;
};
Then MyClassB will have access to the private variables of "MyClass".
If you do something like this:
class MyClass {
public:
MyClass();
~MyClass();
private:
int number;
};
int main(int argc, char *argv[])
{
MyClass A;
A.number = 11; // You can't do this
if(A.number > 10) { // Either you can't do this.
qDebug() << "It's more than 10"; // Qt. well.
}
return 0;
}
You'll get an "error" because you're trying to access A.number from outside of the class.
But if you want to access from some function inside the class:
class MyClass {
public:
myClass() {
number = 10;
if(number > 10) {
qDebug() << "It's more than 10"; // Qt. well.
}
}
~MyClass();
private:
int number;
};

How to access private data members outside the class without making "friend"s? [duplicate]

This question already has answers here:
Can I access private members from outside the class without using friends?
(27 answers)
Closed 6 years ago.
I have a class A as mentioned below:-
class A{
int iData;
};
I neither want to create member function nor inherit the above class A nor change the specifier of iData.
My doubts:-
How to access iData of an object say obj1 which is an instance of class A?
How to change or manipulate the iData of an object obj1?
Note: Don't use friend.
Here's a way, not recommended though
class Weak {
private:
string name;
public:
void setName(const string& name) {
this->name = name;
}
string getName()const {
return this->name;
}
};
struct Hacker {
string name;
};
int main(int argc, char** argv) {
Weak w;
w.setName("Jon");
cout << w.getName() << endl;
Hacker *hackit = reinterpret_cast<Hacker *>(&w);
hackit->name = "Jack";
cout << w.getName() << endl;
}
Bad idea, don't do it ever - but here it is how it can be done:
int main()
{
A aObj;
int* ptr;
ptr = (int*)&aObj;
// MODIFY!
*ptr = 100;
}
You can't. That member is private, it's not visible outside the class. That's the whole point of the public/protected/private modifiers.
(You could probably use dirty pointer tricks though, but my guess is that you'd enter undefined behavior territory pretty fast.)
EDIT:
Just saw you edited the question to say that you don't want to use friend.
Then the answer is:
NO you can't, atleast not in a portable way approved by the C++ standard.
The later part of the Answer, was previous to the Q edit & I leave it here for benefit of >those who would want to understand a few concepts & not just looking an Answer to the >Question.
If you have members under a Private access specifier then those members are only accessible from within the class. No outside Access is allowed.
An Source Code Example:
class MyClass
{
private:
int c;
public:
void doSomething()
{
c = 10; //Allowed
}
};
int main()
{
MyClass obj;
obj.c = 30; //Not Allowed, gives compiler error
obj.doSomething(); //Allowed
}
A Workaround: friend to rescue
To access the private member, you can declare a function/class as friend of that particular class, and then the member will be accessible inside that function or class object without access specifier check.
Modified Code Sample:
class MyClass
{
private:
int c;
public:
void doSomething()
{
c = 10; //Allowed
}
friend void MytrustedFriend();
};
void MytrustedFriend()
{
MyClass obj;
obj.c = 10; //Allowed
}
int main()
{
MyClass obj;
obj.c = 30; //Not Allowed, gives compiler error
obj.doSomething(); //Allowed
//Call the friend function
MytrustedFriend();
return 0;
}
http://bloglitb.blogspot.com/2010/07/access-to-private-members-thats-easy.html
this guy's blog shows you how to do it using templates. With some modifications, you can adapt this method to access a private data member, although I found it tricky despite having 10+ years experience.
I wanted to point out like everyone else, that there is an extremely few number of cases where doing this is legitimate. However, I want to point out one: I was writing unit tests for a software suite. A federal regulatory agency requires every single line of code to be exercised and tested, without modifying the original code. Due to (IMHO) poor design, a static constant was in the 'private' section, but I needed to use it in the unit test. So the method seemed to me like the best way to do it.
I'm sure the way could be simplified, and I'm sure there are other ways. I'm not posting this for the OP, since it's been 5 months, but hopefully this will be useful to some future googler.
In C++, almost everything is possible! If you have no way to get private data, then you have to hack. Do it only for testing!
class A {
int iData;
};
int main ()
{
A a;
struct ATwin { int pubData; }; // define a twin class with public members
reinterpret_cast<ATwin*>( &a )->pubData = 42; // set or get value
return 0;
}
There's no legitimate way you can do it.
Start making friends of class A. e.g.
void foo ();
class A{
int iData;
friend void foo ();
};
Edit:
If you can't change class A body then A::iData is not accessible with the given conditions in your question.
iData is a private member of the class. Now, the word private have a very definite meaning, in C++ as well as in real life. It means you can't touch it. It's not a recommendation, it's the law. If you don't change the class declaration, you are not allowed to manipulate that member in any way, shape or form.
It's possible to access the private data of class directly in main and other's function...
here is a small code...
class GIFT
{
int i,j,k;
public:
void Fun()
{
cout<< i<<" "<< j<<" "<< k;
}
};
int main()
{
GIFT *obj=new GIFT(); // the value of i,j,k is 0
int *ptr=(int *)obj;
*ptr=10;
cout<<*ptr; // you also print value of I
ptr++;
*ptr=15;
cout<<*ptr; // you also print value of J
ptr++;
*ptr=20;
cout<<*ptr; // you also print value of K
obj->Fun();
}
friend is your friend.
class A{
friend void foo(A arg);
int iData;
};
void foo(A arg){
// can access a.iData here
}
If you're doing this regularly you should probably reconsider your design though.
access private members outside class ....only for study purpose ....
This program accepts all the below conditions
"I dont want to create member function for above class A. And also i dont want to inherit the above class A. I dont want to change the specifier of iData."
//here member function is used only to input and output the private values ...
//void hack() is defined outside the class...
//GEEK MODE....;)
#include<iostream.h>
#include<conio.h>
class A
{
private :int iData,x;
public: void get() //enter the values
{cout<<"Enter iData : ";
cin>>iData;cout<<"Enter x : ";cin>>x;}
void put() //displaying values
{cout<<endl<<"sum = "<<iData+x;}
};
void hack(); //hacking function
void main()
{A obj;clrscr();
obj.get();obj.put();hack();obj.put();getch();
}
void hack() //hack begins
{int hck,*ptr=&hck;
cout<<endl<<"Enter value of private data (iData or x) : ";
cin>>hck; //enter the value assigned for iData or x
for(int i=0;i<5;i++)
{ptr++;
if(*ptr==hck)
{cout<<"Private data hacked...!!!\nChange the value : ";
cin>>*ptr;cout<<hck<<" Is chaged to : "<<*ptr;
return;}
}cout<<"Sorry value not found.....";
}

c++ redefine a class

I would like to redefine a class in c++ (non clr). Here's the reason
class BabyClass
{
public:
string Name;
int getSiblings(MainClass &mclass)
{
int c = mclass.size();
for(int i=c;i>0;--i)
{
if(mclass.at(i).Name != Name)
cout << mclass.at(i).Name;
}
}
}
class MainClass
{
public:
vector<BabyClass> babies;
}
now of course this isn't my real code, but I think you can see the problem.
I want my baby class to have access to the main class, the problem is at compile time it doesn't know the MainClass exists, so to fix it normally I would put the MainClass above the BabyClass, but if I do that I can't have a vector of BabyClass's because the compiler wouldn't know about the BabyClass.
I know with functions you can do something like
int function(string hello);
then later
int function(string hello)
{
code
}
or use virtual functions and such. Any idea's how I would do this with classes? Thanks.
And by the way, I know someone is going to ask if it's really necessary, so yes, it is.
Try this arrangement which forward declares MainClass.
class MainClass;
class BabyClass
{
public:
string Name;
int getSiblings(MainClass &mclass);
};
class MainClass
{
public:
vector<BabyClass> babies;
};
int BabyClass::getSiblings(MainClass &mclass)
{
// your code which uses mclass
return 0;
}
int main(){}
BTW, this is not called redefine. The technique is to forward declare and then define it.