Solved

Control class instances

Posted on 2003-11-22
2
229 Views
Last Modified: 2010-04-02
I have a class A, and a class B.  I want to make it so I can only create a class A from class B.  This is how Im trying to do it now:

class A
{
protected:
  A() {};
  A(int i) {};
  ~A() {};
};

class B : public A
{
public:
   B() {};
  ~B() {};
  A* CreateA(int i)
  {
    A* a = new A(i);
    return a;
  }
};

This isnt working though, because it's saying class B cant access protected members of class A (although I thought a derived class could access protected members).  How can I accomplish what Im trying to do?
0
Comment
Question by:lwinkenb
2 Comments
 
LVL 86

Accepted Solution

by:
jkr earned 250 total points
ID: 9804149
>>it's saying class B cant access protected members of class A

Try

class A
{
protected:
 A() {};
 A(int i) {};
 ~A() {};
 A* CreateA (int i) { return new A(i);}
};

class B : public A
{
public:
  B() {};
 ~B() {};
 A* CreateA(int i)
 {
   return A::CreateA(i);
 }
};
0
 
LVL 3

Expert Comment

by:ashoooo
ID: 9804383
B cant access the protected constructor of class A.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

26 Experts available now in Live!

Get 1:1 Help Now