Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++
Hi all,
There are two classes class1 and class2
 
class1()
{
public: 
CV3 Value1;
}
 
class2()
{
//how to access the variable Value1 here?
}
 
 
class1* temp;
temp->variable.x; 
//this gives initialisation error;
Posted 18-Jul-12 2:03am
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

//this gives initialisation error;
 
of course it does. you haven't actually created an instance of an object of type class1. you created a pointer to an object, and they you didn't point it to anything.
 
try this:
class1 temp;
temp.variable.x; 
 
or this:
class1 *temp = new class1;
temp->variable.x; 
  Permalink  
Comments
Member 8446342 at 18-Jul-12 8:36am
   
Thanks, was being a lil silly :P
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

A possible variant Smile | :) :
class A
{
  int m_iVar;
public:
  A(int iVar) : m_iVar(iVar) {}
  int GetVar() const { return m_iVar; }
};
 
class B
{
  A* m_pcA;
public:
  B(A* pcA) : m_pcA(pcA) { ASSERT(m_pcA); }
  int Test() const { return m_pcA ? m_pcA->GetVar() : 0; }
}
 
void Tast()
{
  enum { testVar = 3 };
  A a(testVar);
  B b(&a);
  int iResult(b.Test());
  ASSERT(testVar == iResult);
}
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 4

Also u can make class2 as a friend class of class1 to access members of it.
  Permalink  
Comments
Albert Holguin at 19-Jul-12 10:51am
   
This is only applicable to accessing private members. You also need to already have the object instantiated somehow.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

Why doing all? just inherit class A as parent to class B. so you can access class A public variable using class B object
  Permalink  
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 363
1 Sergey Alexandrovich Kryukov 286
2 RyanDev 75
3 nv3 60
4 PhilLenoir 60
0 Sergey Alexandrovich Kryukov 6,691
1 OriginalGriff 6,119
2 CPallini 2,473
3 Richard MacCutchan 1,697
4 Abhinav S 1,560


Advertise | Privacy | Mobile
Web04 | 2.8.140821.2 | Last Updated 19 Jul 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100