Blender
Оценок: 299
LEARN C++ (BASICS)
От Mehrshad
THIS HAS NOTHING TO DO WITH BLENDER

BUT LATER ON WHEN YOU FIND OUT THAT YOU ALSO NEED TO LEARN PROGRAMMING FOR MAKING GAMES
(IF YOU USE BLENDER TO CREATE MODELS FOR GAME) THIS IS THE GUIDE YOU WANT TO HAVE


edit : thanks for everyone who gave award to this guide hope you guys keep learning in your life , enjoy it , and share it with others

never give up and keep doing it until you are happy with it
7
3
4
5
2
3
2
2
   
Наградить
В избранное
В избранном
Удалить
  • Introduction
Syntax
The following code is written in C++

We shall look at each element of the following code in detail to understand the syntax of C++

#include <iostream> using namespace std; int main() { cout <<"Hello World."; return 0; }

#include <iostream>: This is a header file library. <iostream> stands for standard input-output stream. It allows us to include objects such as cin and cout, cerr etc.



using namespace std: Means that names for objects and variables can be used from the standard library. It is also used as additional information to differentiate similar functions.



int main(): The function main is called just as in C. Any code inside its curly brackets {} will be executed.



cout: is an object used to print a particular text after << in quotes. In our example it will output "Hello World". (for personal reference we can say it is similar to printf in c)



return 0: Terminates the function main



Note:

1) Every C++ statement ends with a semicolon ';'

2) Compiler ignores white spaces. Multiple line spaces are used to make the code more readable.



Omitting Name spaces:

C++ programs run without the standard namespace library. This can be done by writing std keyword followed by :: operator inside int main()

Example:

#include <iostream> int main() { std::cout <<"Hello World"; return 0; }
Output
Using the cout object

As discussed earlier the cout object, together with the << operator, is used to output values/print text.



You can add as many cout objects as you want. However, note that it does not insert a new line at the end of the of each object all of them will be printed in a single line.



Example:

#include <iostream> using namespace std; int main() { cout << "Demo Code."; cout << "I am learning C++."; cout << "Print text."; return 0; }

Output:

Demo Code.I am learning C++.Print text.




New Lines


In order to insert a new line after each object declaration \n is used. Or another way to do so is using end1 manipulator

#include <iostream> using namespace std; int main() { cout << "Demo Code.\n"; cout << "I am learning C++" <<end1; cout << "print text"; return 0; }



Output:

Demo Code. I am learning C++ print text

Note: \n is the preferred way to break lines.

User Input
As we have already discussed earlier cin is used to get user input. This is paired along with the extraction operator (>>)



The following example reads a value from the user and prints it on the screen.

Example:

#include <iostream> using namespace std; int main() { int num; cout << "Type a number: "; // displayed on the screen cin >> num; //value taken from User cout << "Your number is: " << num; // number displayed on the screen return 0; }
  • Fundamentals of c++
Comments
Comments are used by the programmer to make the code understandable so that it can be improvised later and to make it more readable. It can also be used to prevent execution when testing alternative code.



There are two ways to write Comments: singled-lined or multi-lined.



Single line comments



Single-line comments are initiated with two forward slashes (//). This comments the entire line after the two slashes.



Example:

#include <iostream> using namespace std; int main() { // This is a comment and won't be executed cout << "Demo Code"; return 0; }

Output:
Demo Code




Multi Line comments



Multi-line comments start with /* and ends with */



The text in between both of these will not be executed by the compiler. Hence comments can we written in multiple lines



Example:

#include <iostream> using namespace std; int main() { /*This is a multiple line comment it will not be executed */ cout << "Demo Code"; return 0; }


Output:
Demo Code

Variables & Identifiers
Just as in C, there are different types of variables defined with some specific keywords. Variables are defined as 'a data item that may take on more than one value during the run time of a program'. Variable has to be of a specified data type.



int: Stores all kinds of integers e.g. 12, 873

double: Stores floating point numbers which are decimals e.g. 12.3, 16.1
char: Stores single letters, or we can say characters of a string e.g. 'G', 'g'

string: Collection of characters makes a string. These are written in double quotes e.g."Demo Code"
bool: Stored values are either true or false. Shorthand for 'Boolean'.



How to declare a Variable?

Just as in C, we need to mention it's data type followed by the variable and equate it to it's value. However assigning a value to the variable is not necessary.

Syntax:
type variable= value;

Example:

double num=5;

Note: The value of the variable can be overwritten by declaring the variable again later in the code. In order to make the value of variable fixed and avoid over-writting's possibility the const keyword is used.


const int num=5; // num will always be 5 and it's value will not change. If it is overwritten later in the code this will show an error.



C++ Identifiers
Identifiers are the names of functions, variables, structures etc. (the elements we define) used to identify them.

All c++ identifiers must be identified with unique names.

Examples include x,y as well as age, num etc.


Note: Using informative identifiers such as num, age are suggested to increase readability of code.

Rules for constructing identifier names:

1) Can consist of letters, digits and underscores

2) Must begin with a letter or an underscore

3) These are case sensitive

4) Whitespaces or special characters like !, #, %, etc. Are not allowed

5) Reserved words such as int or cout cannot be used as names

Data types
We already introduced data types earlier in the variables section.

Here is an example of a code with all the data types used for revision purpose.

#include <iostream> #include <string> using namespace std; int main () { // Creating variables int _Num = 5; // Integer float _Float = 5.99; // Floating point number double _Double = 9.98; // Floating point number char _Char= 'G'; // Character bool _Bool = true; // Boolean string _String = "Namaste"; // String // Print variable values cout << "int: " << _Num << "\n"; cout << "float: " << _Float << "\n"; cout << "double: " << _Double<< "\n"; cout << "char: " << _Letter << "\n"; cout << "bool: " << _Bool << "\n"; cout << "string: " << _String << "\n"; return 0; }


Space each data type occupies

Int - 4 bytes

Float - 4 bytes

Double - 8 bytes

Char - 1 byte

Bool – 1 byte



Note: Since string is a collection of characters it occupies the space equivalent to that of the addition of the space occupied by each character in that string.





What is the difference between float and Double?



Both of them differ in their size. Float occupies 4 bytes however double occupies 8 bytes. This implies they also differ in the precision they provide. The precision of float is only six decimal digits, while double variables have a precision of about 15 digits. Hence it is safer to use double unless you are concerned about how much memory is being occupied.

Operators
Operators are used in C++ to perform desired operations on particular values or variables.



C++ operators are classified into the following categories:



. Arithmetic operators

. Assignment operators

. Relational operators

. Logical operators

. Bitwise operators

The order of priority given to these operators are:

Assignment > Arithmetic > Relational > Logical > Bitwise


Arithmetic Operators:

Operator
Name
Description
Example
+
Addition
Adds two values
x + y
-
Subtraction
Subtracts one value from another
x - y
*
Multiplication
Multiplies two values
x * y
/
Division
Divides one value from another
x / y
%
Modulus
Returns the division remainder
x % y
++
Increment
Increases the value of a variable by 1
++x
--
Decrement
Decreases the value of a variable by 1
--x

Assignment Operators

These are used to assign values to variables. Often the short hand properties are used to simplify the code.

Short Hand Operator
Example
Same As
=
x = 5
x = 5
+=
x += 3
x = x + 3
-=
x - = 3
x = x - 3
*=
x * = 3
x = x * 3
/=
x /= 3
x = x / 3
%=
x %= 3
x = x % 3
^=
x ^= 3
x = x ^ 3
>>=
x >>= 3
x = x >> 3
<<=
x <<= 3
x = x << 3

Relational Operators

These are used to compare to values. These return values as either true (1) or false (0)

Operator
Name
Description
Example
&&
Logical AND
Returns 1 only if both statements are true
x=5 && x < 10
||
Logical OR
Returns 1 if any one of the statements is true
x < 5 || x < 8
!
Logical NOT
Inverts the given result. Output is 1 for false and 0 for true
!!(x < 5 && x < 10)


Bitwise Operator

Steps to performing Bitwise Operation

1-Convert the numbers into Binary

2-Perform Operation

3-Convert answer into Decimal

Operator
Name
Description
Example
&
Bitwise AND
Performs AND in binary
5&7=5
|
Bitwise OR
Perform OR in binary
5|7=7
^
Bitwise XOR
Performs XOR in binary
5^7=2
<<
Left shift
Shifts one bit to the left
6<<1=12
>>
Right shift
Shifts one bit to the right
6>>1=3
Note:(shortcut for left and right shift)

For left shift multiply the number by 2 for right shift divide the number by 2
Strings
Strings are a collection of characters joint together. They are defined within double quotes. In order to include strings in C++ it is necessary to declare an additional header file <string>.

Syntax:
string name_of_the_string= "text"

Example:

#include <iostream> #include <string> using namespace std; int main() { string str1 = "string"; cout << str1; return 0; }


Output:
string


Note: A string in C++ is actually an object, which contain functions that can perform certain operations on strings.



String Length

The length of a string is found using the length() function



Example:

#include <iostream> #include <string> using namespace std; int main() { string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; cout << "The length of the txt string is: " << txt.length(); return 0; }

Access Characters of a string



We know that a string is an array of characters. Hence a particular character of a string can be accessed by the index number inside the square brackets[ ]. These signify the position of the character.



Example:
#include <iostream> #include <string> using namespace std; int main() { string my_String = "Hello"; cout << my_String[2]; return 0; }

Output:
l //Which is the third element of the string


Alter string characters



Index numbers inside square brackets can be used to change string character.



Example:

#include <iostream> #include <string> using namespace std; int main() { string myString = "Food"; myString[0] = 'G; cout << myString; return 0; }

Output:
Good //G replaced with F


Input a string from a User

Example:

string firstName; cout << "Type your first name"; cin >>firstName;//Scaning a string cout <<"Your first name is<<firstName;


Output:

Type your first name Geetanjali Your first name is Geetanjali





Note: The cin function will only read a single word and the not multiple words. Hence only the first word will be displayed.



String Concatenation

'+' operator is used to add string together.



Example:

#include <iostream> #include <string> using namespace std; int main () { string firstName = "Geetanjali"; string lastName = "Purohit"; string fullName = firstName + lastName; cout << fullName; return 0; }

Output:

GeetanjaliPurohit
Note:

Results of Concatenation



Number + Number = Number

String + String = String

Number + String = Error


Math and Booleans
Find Maximum and Minimum of two numbers
The max(x,y) and min(x,y) can be used to find the highest and lowest values, respectively of x and y.



Examples:



For max(x,y)

#include <iostream> using namespace std; int main() { cout << max(2, 8); return 0; }

Output:
8

Example:



For min(x,y)

#include <iostream> using namespace std; int main() { cout << min(3, 7); return 0; }

Output:

3

Note : In order to introduce other math functions we need to include <cmath> header file



sqrt() : Finds the square root of a number

round() : rounds a number

log() : Finds the logarithm of the number.



Example:

#include <iostream> #include <cmath> using namespace std; int main() { cout << sqrt(16) << "\n"; cout << round(4.2) << "\n"; cout << log(2) << "\n"; return 0; }

Output:
4 4 0.69

Some other important functions included are sin() , cos() , tan() , exp() , pow() and many more including most trigonometric functions.



Boolean Expressions:


These give values as either yes or no, on or off, true or false.

Bool datatype as mentioned earlier gives these values.

#include <iostream> using namespace std; int main() { bool theSunIsHot = true; bool everyoneLikesmonkeys = false; cout << theSunIsHot << "\n"; cout << everyoneLikesmonkeys; return 0; }

Output :

1 0

If---Else
The conditional statement keywords:



Use if to execute the code block if the the condition is true

Use else to execute the code block, if the same condition is false

Use else if to execute a new condition to test, if the previous condition is false




What can the different conditions be?



Less than: a<b

Less than or equal to: a<=b

Greater than: a>b

Greater than or equal to: a>=b

Equal to a==b

Not Equal to: a!=b



The following is an if.. else example

Example:

#include <iostream> using namespace std; int main() { int age = 18; if (age > 18) { cout << "Eligible to Vote"; } else { cout << "Not Eligible"; } return 0; }

The following is an else if..example

Example:

#include <iostream> using namespace std; int main() { int age = 18; if (age < 18) { cout << "Too young."; } else if (age > 81) { cout << "Too old."; } else { cout << "Just right."; } return 0; }

Ternary Operator:

If only one condition/statement is to be executed the conditional operator(ternary operator) can be used instead.



Syntax
variable = (condition) ? expressionTrue : expressionFalse;


Left side of the semicolon will be executed if statement is true else if it is false right side will be executed.



Example :
#include <iostream> #include <string> using namespace std; int main() { int age = 20; string result = (age < 18) ? "Too young" : "Eligible to Vote"; cout << result; return 0; }

Output:
Eligible to vote



Loops
There are three kinds of loops; while, do while and for. These are used to repeat a particular code of block multiple times until the condition satisfies.



While loop



syntax

while ( condition ) { //code block }


The following loop runs till 5 after i=6 the loop's condition becomes false and it no longer works.



Example:

#include <iostream> using namespace std; int main() { int i = 0; while (i < 6) { cout << i << "\n"; i++; } return 0; }

output:

0 1 2 3 4 5


The Do while Loop



This loop will execute the code block once before checking if the condition is true, then for the second time it will repeat the loop as long as the condition is true. Hence the condition is tested after execution



Syntax

do { //code block } while (condition);


Example

#include <iostream> using namespace std; int main() { int i = 0; do { cout << i << "\n"; i++; } while (i < 6); return 0; }


Output
0 1 2 3 4 5


For Loop

This is the most used loop



Syntax


for (Variable value; Condition; increment/decrement operator) { //code block }


Example:

#include <iostream> using namespace std; int main() { for (int i = 0; i <= 5; i++) { cout << i << "\n"; } return 0; }


Output
0 1 2 3 4 5
Switch
Switch statement is used to select one of many code blocks to be executed. This can be used as an substitute for if.. else statements and vica-versa.



Syntax

switch (variable) { case 1: //code block break; case 2: //code block break; default: //code block }


What happens? The variable's value is compared with that of each case. Whichever case matches the value, that code block is executed.




Important Keywords

break: it breaks out of the switch block so that all the codes of other cases aren't executed.

default: This sets a standard code, which is executed if none of the other cases are executed.


Example:


#include <iostream> using namespace std; int main() { int day = 5; switch (day) { case 1: cout << "Monday"; break; case 2: cout << "Tuesday"; break; case 3: cout << "Wednesday"; break; case 4: cout << "Thursday"; break; case 5: cout << "Friday"; break; case 6: cout << "Saturday"; break; case 7: cout << "Sunday"; break; } return 0; }

Output:

Friday

Break and Continue
Break: We already discussed about one of the use of this statment earlier.The break statement can also be used to jump out of a loop.

#include <iostream> using namespace std; int main() { for (int i = 0; i <= 10; i++) { if (i == 6) { break; } cout << i << "\n"; } return 0; }


Output

0 1 2 3 4 5

Continue: The continue statement breaks one time repetition of the loop if a specified condition occurs and continues with the next iteration in the loop.



Example

#include <iostream>

using namespace std;

int main()
{
for (int i = 0; i <= 10; i++) {
if (i == 6) {
continue;
}
cout << i << "\n";
}

return 0;

}

Output

0 1 2 3 4 5 6 7 8 9 10

Array
Arrays follow contiguous memory allocation ( a classical memory allocation model that assigns a process consecutive memory block ). They are used to store multiple values in a single variable.



Value in the square bracket specifies the number of elements in the array.


Way to Define a array.



For strings

string fruits[3] = {"Banana", "Mango, "Apple"};

For number

int Num[3] = {10, 56, 12};

Access the elements of a array



Elements of a array are accessed by referring to the index numbers.



Example:

#include <iostream>
#include <string>

using namespace std;

int main()
{
string fruits[3] = {"Banana", "Mango", "Apple"};
cout << fruits[0];
return 0;
}

Output:
Banana


Change an array element

This is also done by referring to index numbers



Example:

#include <iostream> #include <string> using namespace std; int main() { string fruits[3] = {"Banana", "Mango", "Apple"}; fruits[0] = "Orange"; cout << fruits[0]; return 0; }


Output:
Orange


Loops and Arrays

Array elements can be looped.



Example:



#include <iostream> #include <string> using namespace std; int main() { string fruits[3] = {"Banana", "Mango", "Apple"}; for(int i = 0; i < 4; i++) { cout << fruits << "\n";
}
return 0;
} [/code]


Output:

Banana Mango Apple


Note: Array's size doesn't have to be defined inside the square bracket. But if it is not defined it will only be as big as the elements that are inserted into it.



In the following code 3 is the arrays maximum size. However if the size is specified the array will occupy that much space even if space is left empty.


Example:

string fruits[] = {"Banana", "Mango", "Apple"};



Pointers and references
References
The & operator is used to create references. References are like alias of a variable. i.e you can refer same variable via the reference variable.


Example:

string subject="Math"; //subject variable string &study= subject; //Reference to subject


Now either 'subject or study can be used to refer to the subject variable. Hence value of it which is maths can be got by any of these two methods.


Example:

#include <iostream> #include <string> using namespace std; int main() { string subject= "Math"; string &study = subject; cout << subject << "\n"; cout << study << "\n"; return 0; }

Output:
Math Math

Memory Address



When a variable is created in C++, it occupies some memory and hence it is allocated a particular location, where it is stored. & is used to get the memory address of a variable; which is the location of where the variable is stored.



Example :

#include <iostream> #include <string> using namespace std; int main() { string food = "Panipuri"; cout << &food; return 0; }

Outpot :

0x5dged3


Note:The location is in hexadecimal form. The location of storage will vary every time and so the display of output will show different values.



Creating Pointers:



A pointer is a variable that stores the memory address as its value.



The pointer is created using *. It points to an address of the same datatype variable. The address is then assigned to the pointer.



Example:


#include <iostream> #include <string> using namespace std; int main() { string food = "Panipuri"; // A string variable string *p = &food; // A pointer variable that stores the address of food // Output the value of food cout << food << "\n"; // Output the memory address of food cout << &food << "\n"; // Output the memory address of food with the pointer cout << ptr << "\n"; return 0; }

Output:

Panipuri 0x7def3 0x7def3

Note

* Does two different things in the code:

When used in declaration (string* p), it creates a pointer variable and points to an address.

When not used in declaration, it act as a operator which gives the value at a given address.





  • Functions
Functions
The purpose of creating a function is so that a block of code can be executed multiple times when a function is called.



Data known as parameters is passed into the function.



The function main() is predefined and is mandatory in program. However there are other functions which are user defined.



How to create a function?

Syntax:

void nameFunction() { //code block }


Note: Void means the function doesn't have a return value





Function Calling



To call a function we are to write the function's name followed by brackets () and a semicolon;



Example:

#include <iostream> using namespace std; void myFunction() { cout << "We are learning functions"; } int main() { myFunction(); return 0; }


Output:
We are learning functions

Note: The function can be called multiple times and that's what makes it useful.



Example

#include <iostream> using namespace std; void myFunction() { cout << "We are learning functions"; } int main() { myFunction(); myFunction(); myFunction(); return 0; }

Output:

We are learning functions We are learning functions We are learning functions

Note: If a user-defined function as in the above example is declared after the main() function the code will throw an error. It is because C++ works from top to bottom in a sequential flow.



Hence another way of writing the function, if the function is written below main() is :



Example:

#include <iostream> using namespace std; // Declaration of the Function void nameFunction(); // Main before the function int main() { nameFunction(); // call the function return 0; } // Function void nameFunction() { cout << "We are learning functions"; }



Function Parameters
Data can be passed to a function as a parameter. These are variables inside of functions. These are specified withing the brackets with their datatypes.



Syntax:

void function( datatype variable; datatype variable;) { //code block }

In the following example Honey is an argument , however name is a parameter

Example:


#include <iostream> #include <string> using namespace std; void function(string name) { cout << name << " surname\n"; } int main() { myFunction("Honey"); myFunction("sam"); myFunction("Anja"); return 0; }

Outpot :

Honey surname sam surname Anja surname

Return Values



In the following example the keyword return is used. Using int instead of void helps us to derive a return value. However as discussed earlier void doesn't return a value.



Example:

#include <iostream> using namespace std; int myFunction(int x, int y) { return x + y; } int main() { int z = myFunction(2, 3); cout << z; return 0; }


Outpot :
5

Call by Reference



You can also pass a reference to the function by using pointers of such as in the following example:

#include <iostream> using namespace std; void swapNums(int &x, int &y) { int z = x; x = y; y = z; } int main() { int firstNum = 10; int secondNum = 20; cout << "Before swap: " << "\n"; cout << firstNum << secondNum << "\n"; swapNums(firstNum, secondNum); cout << "After swap: " << "\n"; cout << firstNum << secondNum << "\n"; return 0; }


Output:

Before swap: 1020 After swap: 2010

Function Overloading
This property is special to C++. Using Function overloading multiple functions can have the same name with different parameters.



Example:


#include <iostream> using namespace std; int addFunc(int a, int b) { return a + b; } double addFunc(double a, double b) { return a+b ; } int main() { int num1 = addFunc(3, 5); double num2 = addFunc(2.1, 6.2); cout << "Int: " << num1 << "\n"; cout << "Double: " << num2; return 0; }

Output:
Int : 8 Double : 8.3

Note: It is better to over load one function instead of defining two functions to do the same thing. Remember multiple functions can have the same name until their datatype or parameters differ.

  • C++ Class
Classes/Objects
What is object oriented programming?



This consists of creating objects that contain data and functions. This is different from procedural programming that performs operations on data sequentially. Classes and objects are two main aspects of object oriented programming.



Example:



Class: Fruits

Objects: Apple, Mango, Cherry



Another aspect of this programming is attributes (e.g. Color and size) and methods (e.g. Break and speed) of various objects.



Create a Class



To create a class we use the keyword class.



In the following example the class keyword is used to create a class. Public is the access specifier (In detail later in this module). The variables declared within the class Num and Name_string are attributes. At last use of a semicolon is mandatory.



Example:

class Name_Class //The class { public //Acess specifier int Num; //Attribute string Name_string; //Attribute };

Create a object



An object is created from a class



The syntax includes creating an object of Name_class specify the class name, followed by the object name.



We can access the class attributes using (.) on the object



Example:

#include <iostream> #include <string> using namespace std; class Name_Class //The class { public: //Acess specifier int Num; //Attribute string Name_string; //Attribute }; int main() { Name_Class my_Obj; // Create an object of Name_Class // Access attributes and set values my_Obj.Num = 16; my_Obj.Name_string = "Demo Code"; // Print values cout << my_Obj.Num << "\n"; cout << my_Obj.Name_string; return 0; }

Output:


16 Demo Code

Class Methods
Methods are functions that belongs to the class.

Functions can be defined inside of class or outside it. You can access methods exactly the same way you access classes by using (.)




Inside Class Definition

Example:
#include <iostream> using namespace std; class My_Class { // The class public: // Access specifier void My_Method() { // Method(function) cout << "Namaste!"; } }; int main() { My_Class myObj; // Create an object of MyClass myObj.My_Method(); // Call the method return 0; }


Outside Class Definition



Example:

#include <iostream> using namespace std; class My_Class // The class { public: // Access specifier void my_Method (); // Method/function declaration }; // Method/function definition outside the class void My_Class::my_Method () { cout << "Namaste!"; } int main () { My_Class myObj; // Create an object of MyClass myObj.my_Method (); // Call the method return 0; }

Note: As in functions parameters can be here as well

Access Specifiers
The public keyword that occurs in all our class examples is our access specifier. Access specifiers defines the accessibility of classes, methods, and other members.



There are three kinds of access specifiers in C++



1) Public : members can be accessed (or viewed) from outside the class

2) Private : members cannot be accessed (or viewed) from outside the class

3) Protected : members cannot be accessed from outside the class, however, they can be accessed in inherited classes. (We can define inherited classes as those which inherit attributes and methods from one class to another.)



We have already looked at examples of public. We will look at the private access specifier with an example:



Example:

#include <iostream> using namespace std; class My_Class { public: // Public access specifier int a; // Public attribute private: // Private access specifier int b; // Private attribute }; int main() { My_Class my_Obj; my_Obj.a = 16; // Able to view it(a is public) my_Obj.b = 2002; // Not allowed to view it (b is private) return 0; }

outpot:
error
main.cpp: In function ‘int main()’: main.cpp:19:10: error: ‘int My_Class::b’ is private within this context my_Obj.b = 2002; // Not allowed to view it (b is private) ^ main.cpp:10:9: note: declared private here int b; // Private attribute ^
Class Constructors


This is a special method. Called once an object of a class is created. In order to create a constructor use the same name as the class, followed by brackets ().



Example:
#include <iostream> using namespace std; class My_Class // The class { public: // Access specifier My_Class() // Constructor { cout << "Demo Code"; } }; int main() { My_Class myObj; // this will automatically call the constructor return 0; }

output:
Demo Code



Note: Just like regular functions constructors can also take parameters which can be used for initialising values for attributes.



Note: Constructors can be defined outside the class however it has a different syntax.



Steps:

1-Declare the constructor inside the class

2-Define it outside of the class by mentioning the name of the class

3-Use :: operator, followed by the name of the class


Example:

#include <iostream> using namespace std; class Phone { // The class public: // Access specifier string brand; // Attribute string model; // Attribute int year; // Attribute Phone(string a, string b, int c); // Constructor declaration }; // Constructor definition outside the class Phone::Phone(string a, string b, int c) { brand = a; model = b; year = c; } int main() { // Create Phone objects and call the constructor with different values Phone PhoneObj1("Nokia", "008", 1899); Phone PhoneObj2("Samsung", "Galaxy", 1969); // Print values cout << PhoneObj1.brand << " " << PhoneObj1.model << " " << PhoneObj1.year << "\n"; cout << PhoneObj2.brand << " " << PhoneObj2.model << " " << PhoneObj2.year << "\n"; return 0; }


Output:

Nokia 008 1899 Samsung Galaxy 1969

Class Destructor
Class Destructor as it's name suggests is a function which deletes an object.



A destructor function is called when
(1) Function ends
(2) Program ends
(3) Block consisting of local variables ends
(4) Delete operator is called



Destructors have same name as the class only with a tilde (~)

Destructors do not allow parameters and only one destructor in a class.



Example:
#include <iostream> #include <string.h> class string { private: char *s; int size; public: string(char *); //constructor ~string(); //destructor }; string::string(char *c) { size = strlen(c); s = new char[size+1]; strcpy(s,c); std::cout<<"constructor called\n"; } string::~string( ) { std::cout<<"desctructor called"; delete [ ]s; } int main() { string str("name"); }
Class Inheritance
As mentioned earlier, inheritance is handy in understanding the role of the 'protected' access specifier. It is possible to inherit attributes and methods from one class to another.



There are two important terms for it's description:



Derived class : Inherited from another class

Base class: Class being inherited from



This can be understood better from the parent child analogy. Parents are the ones passing on their characteristics to us and we inherit them. Hence Derived class is the child and Base class the parent.



We use the colon (:) symbol to inherit from a class



Example:
#include <iostream> #include <string> using namespace std; // Base class class Food { public: string brand = "Dominos"; void ready () { cout << "Pizza is ready! \n"; } }; // Derived class class Junk_food:public Food { public: string place = "4D square"; }; int main () { Junk_food my_food; my_food.ready (); cout << my_food.brand + " " + my_food.place; return 0; }


Output:
Pizza is ready! Dominos 4D square

Multi-level Inheritance:



A class can also be derived from a class, which is already derived from another class.



Example

#include <iostream> using namespace std; // Base class class My_mom { public: void my_Function () { cout << "Mother"; } }; // Derived class class Me:public My_mom { }; // My child class MyChild:public Me { }; int main () { MyChild myObj; myObj.my_Function (); return 0;

Output:

Mother


Multiple Inheritance



Class derived from multiple base class, using a comma separated list



Example:

#include <iostream> using namespace std; // Base class class MyClass { public: void myFunction () { cout << "Base Class 1\n"; } }; // Another base class class MyOtherClass { public: void myOtherFunction () { cout << "Base Class 2\n"; } }; // Derived class class MyChildClass:public MyClass, public MyOtherClass { }; int main () { MyChildClass myObj; myObj.myFunction (); myObj.myOtherFunction (); return 0;


Output:

Base Class 1 Base Class 2
NOTES
even if you sit and read this 10 times you cant do anything with it you have to start coding

how should i use this guide

1 hour every day each day one part first understand the thing and then copy the code
run it and make another verison yourself without any help when you fully understand the thing
move to the next part

dont go over 1 hour of work each day

have nice day.

Комментариев: 62
Mehrshad  [создатель] 23 мар в 10:09 
;/
nevafel 23 мар в 10:08 
NOO DON'T LISTEN TO HIM YOU FOOLS!!!
YOU SHOULD LEARN RUST!! RUST IS MEMORY SAFE MUCH EASIER AND.. AND... NKASndancla;cnl;aclanc a
oapmcokancioascmklzxcm zlxcnmzcklzdmclcmkmlanclamc
Mehrshad  [создатель] 22 мар в 23:35 
@chersbobers (• ω •) enjoy make sure you showup everyday (meaning never give up)
chersbobers 22 мар в 14:17 
im a programmer(ish) this is really in depth.
cockslav 14 мар в 5:41 
ладно
BT 7274 3 мар в 23:32 
wow amazaing
willzwix1 10 янв в 18:37 
...wow
mak 7 янв в 13:42 
woaw
Mehrshad  [создатель] 4 янв в 8:51 
enjoy
Geschlechtlos 2 янв в 5:13 
Well umm..thank you. I actually have to pass C++ for uni so i might come back to you... But Why Are you here...