Click here to Skip to main content
15,886,007 members
Please Sign up or sign in to vote.
1.33/5 (3 votes)
See more:
Here's my code (ignoring headers and the types):

C++
class A {
public:
    A(); //constructor
    memberfunc1();
    memberfunc2();
};

class B : A
{ //ie inherits from base class A
public:
    B()
    {
        A *pA = new A[3]; //ok so ive got 3 A objects with pointer to them pA right? wrong?
    };
}

main()
{
    B * pB = new B[2]; // creates 2 B objects each containing 3
}

This all works fine but I'm unsure what to do for the following:
1. I want to determine the object A[0] to do memberfunction1
2. I want to make objects A[1] and A[2] do memberfunction2

Is this possible? Also, please can you explain what the two pointers I declared actually point to? I origionally thought they just declared themselves as pointers to the classes which could then point onwards. Is this right? They do what I wanted but I am uncomfortable in the uncertainty of why... and when I try to do *pB->memberfunc1; it messes up with errors... Please feel free to make a different example code. I just want to get the understanding and everything I find online is to do with a single object - not an array of them. Many thanks!
Posted
Updated 28-Oct-12 15:49pm
v2

Does this help clear up your confusion?

C++
#include <stdio.h>
#include <stdlib.h>

class A {
public:
    A() {}; //constructor
    void memberfunc1(){printf("A:memberfunc1\n");}
    void memberfunc2(){printf("A:memberfunc2\n");}
};

class B : public A
{ //ie inherits from base class A
    A *pA;
public:
    B()
    {
        pA = new A[3]; //ok got an array holding 3 instances of class A
    };
    ~B()
    {
        delete [] pA;     // we don't want the memory any more since this is the destructor. Giv the mem back
    }

    void showAll()
    {
        int i;
        for (i=0; i<3; i++)
        {
            printf("-------- Callling member functions of pA[%d]--------\n", i);
            pA[i].memberfunc1();
            pA[i].memberfunc2();
        }
    }
};

int main()
{
    B *pB = new B[2]; // creates 2 B objects each containing 3

    printf("=======***** Calling member function of pb[0] ****=======\n");
    pB[0].showAll();
    printf("=======***** Calling member function of pb[1] ****=======\n");
    pB[1].showAll();

    delete [] pB;       // we allocated mem, so we have to free it too, since they're allocated on the heap
}


Also, to address your questions:

Is this possible? ( A[0] call memberfunction1, A[1] & A[2] call memberfunction2)
Sure is, compile the code and give it a whirl.

What do these two pointers actually point to?
They're no more than a pointer to the first element in the array. Because of the way they're (the arrays) declared, the compiler doesn't know how many elements are in each array.

Consider the following snippet:
C++
char str1[] = "This is a 24 char string";
char *str2 = strdup(str1);
char *str3 = new char[strlen(str1)+1];
strcpy(str3, str1);
printf("sizeof(str1) = %d\n", sizeof(str1) );
printf("sizeof(str2) = %d\n", sizeof(str2) );
printf("sizeof(str3) = %d\n", sizeof(str3) );

Output:
sizeof(str1) = 25
sizeof(str2) = 4
sizeof(str3) = 4


You need to be careful with how you interpret these results - while it's true that all three of them are pointers, the behaviour of the sizeof operator muddies the water somewhat. I won't try to explain, for fear of making them even murkier..


Hope this helps alleviate, rather than adding to your confusion. :)
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 28-Oct-12 23:23pm    
I think it does, my 5.
Perhaps OP needs tighter understanding OOP with C++, in particular, how instance (non-static) functions work, that is, passing "this" as a hidden parameter, and the type if "this" in case of inheritance.
--SA
Eugen Podsypalnikov 29-Oct-12 2:57am    
Only 3 as a help for the beginner :) :
- there is no explanation about the wrong used term "pointer to a member function"
- there are no deallocations in the provided code (= memory leaks)
enhzflep 29-Oct-12 3:10am    
Sounds fair to me. They're both very good points. I'd mused over what details to ignore and which to supply in the interests of keeping the answer short and succinct. Thanks for letting me know I may have erred on the wrong side here. I'll fix it.
Thank-you!
Just to clear up a misunderstanding that isn't covered in the otherwise excellent solution 1:

When you declare a member function in a class, this is not a function pointer! And you cannot use it as such. That is why a member function is - perhaps more appropriately - called a 'method'. Instead, such a declaration is pretty much the same as a simple (global) function declaration: just a prototype that defines the signature of the function, with enough information on how to call it from elsewhere.

C++
// example 1: global variable
int v;
// example 2: global function declaration
void global_func1(int x); // only signature here
// example 3: global function declaration and implementation combined
int get() {
   return v;
}

// implementation for example 2:
// (this may be moved anywhere in your code)
void global_func1(int x) {
   v = x;
}

class A {
private: // declare the following as restricted; may only be used 'inside' the class
   // example 4: member variable
   int value;    // declaration of a 'private' member variable
public:  // declare the follwing as accessible from anywhere
   // example 5: member function declaration
   void member_func(int x);
   // example 3: member function signature and implementation combined
   int get() const {
      return value; // note that the 'private' variable value can be accessed here
   }
};

// implementation for example 5:
void A::member_func(int x) {
   value = x; // note that the 'private' variable value can be accessed here
}


int main() {
   // ex. 1: access global variable
   v = 7;
   // ex. 2: call global function
   global_func(3); // sets v to 3
   // ex. 3: call other global function
   int x = get(); // sets x to 3

   A a[3]; // defines array of 3 objects of type 'class A'
   // ex. 4: accessing member variable - this is not possible here!
   // ...
   // ex. 5: call member function, on different objects
   a[0].member_func(4); // call the function, using first object
                        // now a[0].value is equal to 4
   a[1].member_func(5); // call function on second object ...
                        // now a[1].value is equal to 5, while a[0].value is still 4
   a[2].member_func(6); // ... and on third object
                        // a[2].value is now 6
   // ex. 6: call other member function
   int y = a[1].get(); // sets y to 5
   int z = a[2].get(); // sets z to 6

   return 0;
}

You can see various things about member functions:
1. calling a member function (usually) requires an object that you call it 'on'
2. it doesn't involve function pointers
3. calling a member function may modify the state of the object it is called on, and only of that object - other objects are unaffected.
4. In comparison, a global function will/can always affect the global state only (i. e. global variables)
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900