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 3: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 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
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.

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

  Print Answers RSS
0 Maciej Los 347
1 DamithSL 305
2 ridoy 278
3 OriginalGriff 224
4 George Jonsson 140
0 OriginalGriff 7,968
1 DamithSL 6,179
2 Sergey Alexandrovich Kryukov 5,524
3 Maciej Los 5,438
4 Kornfeld Eliyahu Peter 4,539


Advertise | Privacy | Mobile
Web04 | 2.8.141223.1 | 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