Pointer and the C++ Philosophy

来源:互联网 时间:2018-03-01

Object-oriengted programming differs from traditional procedural programming in that OOP emphasizes making decisions during runtime instead of during compile time.
Runtime means while a program is running,and compile time means when the compiler is putting a program together.
A runtime decision is like,when on vacation,choosing what sights to see depending on the weather and your mood
at the moment,whereas a compile-time decision is more like adhering to a preset schedule,regardless of the conditions.
Runtime decision provide the flexibility to adjust to current circumstances.For examle,consider allocating memory for an array.The traditional way is to declare an array.To declare an array in C++,you hava to commit yourself to a particular array size.Thus,the array size is set when the program is compiled;it is a compile-time decision.
Perhaps you think an array of 20 elements is sufficient 80% of the time but that occasionallthe program will need to handle 200 elements.To be safe,you use an array with 200 elements.This results in your program wasting memory most of the time it's used.OOP tries to make a program more flexible by delaying such decisions until runtime.That way,after the program is running,you can tell it you need only 20 elements one time or that you need 205 elements another time.
In short,with OOP you would like to make the array size a runtime decision.To make this approach possible,the lanage has to allow you create an array——or the equivalent——while the program runs.The C++ method,as you soon see,involves using the keyword new to request the correct amount of memory and using pointers to keep track of where the newly allocated memory is found.
Making runtime decision is not unique to OOP.But C++ makes writing the code a bit more straightforward than does C.