In: Computer Science
5.
Assignment Instructions:
Please respond with at least 100 words. Your initial post should address each of the topic below thoughtfully.
Topic: With the advent of object-oriented programming, is it ever necessary to use C-type structs rather than classes? If so, when? What are the advantages or disadvantages of each approach?
In Object Oriented Programming,
Structure is the same as a Class except for a few differences.
1)The most important of them is security. Structure is not secure and cannot hide its implementation details from the end user while a class is secure and can hide its programming and designing details it means Members of a class are private by default and members of a struct are public by default. Please see below Example in case of security:
class Test {
int x; // x is private
};
int main()
{
Test t;
t.x = 20; // compiler error because x is private
getchar();
return 0;
}
======================================================================
struct Test {
int x; // x is public
};
int main()
{
Test t;
t.x = 20; // works fine because x is public
getchar();
return 0;
}
========================================================================
2) When deriving a struct from a class/struct, default access-specifier for a base class/struct is public. And when deriving a class, default access specifier is private
class Base {
public:
int x;
};
class Derived : Base { }; // is equilalent to class Derived : private Base {}
int main()
{
Derived d;
d.x = 20; // compiler error becuase inheritance is private
getchar();
return 0;
}
=====================================================================
class Base {
public:
int x;
};
struct Derived : Base { }; // is equilalent to struct Derived : public Base {}
int main()
{
Derived d;
d.x = 20; // works fine becuase inheritance is public
getchar();
return 0;
}
========================================================================
3)Class can create a subclass that will inherit parent's properties and methods, whereas Structure does not support the inheritance i.e. Class can be a Parent Class and derived Classes can inherit this Class in Inheritance but Structure cannot be a Parent Class so it won't be a part of Inheritanc
4)Structs are best suited for small data structures that contain primarily data that is not intended to be modified after the struct is created
5)Structs is created on stack while Class is on Heap so it is faster to instantiate (and destroy) a struct than a class