C++ topics..

Hello Experts,

I want to know the following things in C++..
1) What is encapsulation?
2) what is abstraction?
3) what is aggregation?
4) what exactly is the use of abstract class in C++ and also with virtual functions?

I apprecitate if some one  can explain with a good example..
5)
tatikor_143Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Infinity08Commented:
>> 1) What is encapsulation?

It refers to grouping data and the methods working on that data together. C++ provides classes for that purpose (using the public, private and protected access specifiers).

For example :

        class Student {
            private :                             // a few data members defining a student
                std::string name;
                int age;
                std::vector<Class*> classes;

            public :                               // the functionality for a student - what can a student do ?
                void enrollToClass(Class &c) {}
                void graduate() {}
        };


>> 2) what is abstraction?

It refers to writing a well defined interface that hides the internal implementation - ie. the user does not need to know how the interface is implemented - he just has to know how he should use the interface.

More specifically, this methodology is used in the development process by identifying different parts of an application, splitting up those parts in smaller parts, splitting those smaller parts up again, etc. Each of these parts is then implemented separately, and they can interface with other parts by simply knowing the interfaces of those other parts (not their implementation).

Note that C++ has abstract classes (a class containing one or more pure virtual methods) for this purpose which define an interface that needs to be implemented in the derived class(es).

For example :

        class Car {
            public :
                virtual void drive() = 0;      /* <--- a car HAS to be able to drive */
        };

        class Volkswagen : public Car {
            public :
                virtual void drive() { /* here comes the implementation how a Volkswagen drives */ }
        };

        class Renault : public Car {
            public :
                virtual void drive() { /* here comes the implementation how a Renault drives */ }
        };

The Car base class specifies the interface - ie. a car has to be able to drive - but it doesn't specify the implementation (how it will drive). Every specific type of car, deriving from the Car class, will have to implement that drive functionality.


>> 3) what is aggregation?

Aggregation is similar to composition (containing an object in another object), but differs with it in that the object can just contain a reference or a pointer to another object. This implies that the objects referred/pointed to will not be destroyed with the main object.

For example :

        class Student {

        };

        class School {
            std::vector<Student*> students;
        };

A School objects contains a list of pointers to Student objects that are enrolled in that school.


>> 4) what exactly is the use of abstract class in C++ and also with virtual functions?

See the answer to 3). Virtual functions are a way of providing different implementations for different polymorphic classes. In the above Car example eg. the Volkswagen and the Renault classes can implement the drive() method differently.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Infinity08Commented:
>> See the answer to 3).

Should have been "See the answer to 2)." of course :)


I also forgot an example for 4) - Her it is (using the same classes as in 2) ) :

        std::vector<Car*> carpark;
        carpark.push_back(new Volkswagen());
        carpark.push_back(new Renault());

        // the car park now contains a Volkswagen and a Renault

        // we can drive both without knowing the type :
        carpark[0].drive();
        carpark[1].drive();

Both cars in the car park will now drive in their own specific way (according to the implementations for a Volkswagen and a Renault respectively).
0
kaylanreilorCommented:
You should first buy a book and try to understand OO programming. The goal when defining some classes is always to modelize systems with a specific behaviour viewed from outside. An object get some entries commands, provides some outputs and has a proper inside mechanism to obtain such a behaviour. So you should get some knowledges on : what is interfaces programming too. The interface of your radio is the panel with the buttons, and the implementation is the whole electronics inside.
Thus :

1) Encapsulation is the way you hide some members of your from outside. Then, all the members you decide to make public can be considered as part of the interface of your class, the other are protected from another object dealing with them.

3) Let's imagine that you define 2 classes : a car and a clutch system. A car own a clutch system. The interface of the clutch system is the lever. The car own the clutch system and expose its interface to you. So when you have a class which has a member of another class and expose the interface of this "member object" => this is aggregation. Again, let's read some stuffs about interfaces programming and/or COM.

4) Mainly, the abstract classes are used to define interfaces ! Hi, hi ! Actually, when a class is abstract it can not be instanciated (you cannot have an object of this class) and it is supposed to become the base class of another one. We say that this other class implement this abstract class because this derived class will have to defined all the methods declared as pure virtual in the base class. So the use is to say, we are going to defined a system which will expose this set of methods, so in a macro-system all the objects which implement all this methods will be usefull for these other modules. Now, let's imagine that your company decide to develop some drivable vehicules. Your boss will describ the interface common for any kind of vehicule in saying that these vehicules will expose a steering wheel, a clutches level, a brake pedal, an accelerator pedal and the behaviour of the vehicules each time you use these member of the Drivable_Interface. This Drivable_Interface will be an abstract class, we will say that it defines an interface, and all the classes that will define any kind of the vehicule that the company will developp will implement this interface. Doing stuffs this way, another company will developp some drivers with some interfaces for these drivers and god himself will be abble to make the drivers and the vehcules match. Now, in your company some experienced developpers will defined classes like cars, trucks and bus and all these different vehicules will implement the Drivable_Interface. But the implementation of these classes can be different because the brake system on a trucks is different compared to a brake system on a car whever both of them have the same behaviour.

In C++ a class which owns at least one pure virtual method is abstract. If you try to create an object of such a class the compiler will complain saying that you cannot instanciate an object from an abstract class. Generally speaking, a virtual function in a base class is overridable in a derived class. A pure virtual function MUST be defined in a derived class. Imagine your car exist and it has a clutch pedal which do something. It is defined in the base class of the car. Now, your company wants to develop a new type of car with automatic clutchs. Then the new class will be able to inherit from the existing one if the methods concerning the actions on the clutch pedal are virtual (not pure) because in the new implementation of this method, that you will override, you will code something like "Do nothing".

But again, you should spend 1 or 2 months to read some books to definitely get some knowledge on these topics which have to do with the oriented object programming. These concept exist in all the OO langages so it's not specific to C++. It's only one time in your life, I'm not saying that you should read a bible each time you have a question.

More straighforward, you can search for the keyword "virtual" in the MSDN (and abstract too).

Here is a code showing the use of a virtual method:
class A
{
public:
	virtual void SayHello()
	{
		cout << "Hello A." << endl;
	}
};
 
class B : public A
{
public:
	virtual void SayHello()
	{
		cout << "Hello B." << endl;
	}
};
 
class C : public A
{
};
 
int main()
{
	A a;
	B b;
	C c;
	a.SayHello();
	b.SayHello();
	c.SayHello();
return 0;
}
 
// Then the output is
Hello A.
Hello B.
Hello A.

Open in new window

0
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

Infinity08Commented:
Can I ask you why you gave a B grade ? That usually means that the answer given was not sufficient (didn't address your question completely).

If there are still questions left, you can always ask for clarification - you do not need to accept a reply as long as the question hasn't been answered yet.
0
kaylanreilorCommented:
Have a look to the time stamp of the posts.
0
Infinity08Commented:
What does a B grade have to do with timestamps ?
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.